简体   繁体   中英

How to define type conversion to string for a custom type

Can I define how a conversion to string, using String() would be applied to my custom type myint ? And how to do so?

I was expecting to define the method String() to be enough as it is used by fmt.Println() but apparently not by string() . This is purely a theoretical question as I am learning Go and was surprised by this behavior.

Here is an example showing the behavior:

package main

import (
    "fmt"
)

type myint int

func (m myint) String() string {
    return fmt.Sprintf("%d", m)
}

func main() {
    var val myint = 42
    mystr := "Testing: " + string(val)
    fmt.Println(mystr, val)
}

Which outputs:

Testing: * 42

But I was expecting:

Testing: 42 42

Can I define how a conversion to string, using string() would be applied to my custom type myint ? And how to do so?

No, you can't "override" conversion behavior. It's recorded in Spec: Conversions , and that's the end of it. The String() method works for the fmt package because the fmt package is written to explicitly check for the presence of the String() string method. Conversions don't do that.

If you need custom conversion behavior, don't use conversion, but implement your logic in methods (or functions), and call those methods (or functions).

So in your example you would write:

mystr := "Testing: " + val.String()

And you would get your expected output (try it on the Go Playground ):

Testing: 42 42

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