简体   繁体   中英

Golang: convertor function

We have some structure S . Is it possible to make a converter so that the expression

s := S(a_string) 

began to compile, where a_string is actually a string .

The allowed conversions are listed in Spec: Conversions . There's a section for "Conversions to and from a string type" . Only those are allowed, you can't "extend" or change the behavior of conversions.

You may however always write a function that takes a string and returns a value of type S .

func Parse(s string) S {
    var r S
    // Parsing logic
    return r
}

Using it is / looks like the same as a conversion:

s := Parse(a_string)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM