简体   繁体   English

如何为自定义类型定义类型转换为字符串

[英]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 ?我可以定义如何使用String()将转换为字符串应用于我的自定义类型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() .我期望将方法String()定义为足够,因为它被fmt.Println()使用,但显然不是被string()使用。 This is purely a theoretical question as I am learning Go and was surprised by this behavior.这纯粹是一个理论问题,因为我正在学习 Go 并对这种行为感到惊讶。

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测试:* 42

But I was expecting:但我期待:

Testing: 42 42测试:42 42

Can I define how a conversion to string, using string() would be applied to my custom type myint ?我可以定义如何使用string()将转换为字符串应用于我的自定义类型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.它记录在Spec: Conversions中,这就是它的结尾。 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. String()方法适用于fmt package,因为fmt package 是为了显式检查String() string方法的存在而编写的。 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 ):你会得到你所期望的 output (在Go Playground上试试):

Testing: 42 42

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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