在 Go 中将自定义类型转换为字符串

新手上路,请多包涵

在这个奇怪的例子中,有人创建了一个新类型,它实际上只是一个字符串:

 type CustomType string

const (
        Foobar CustomType = "somestring"
)

func SomeFunction() string {
        return Foobar
}

但是,此代码无法编译:

不能在返回参数中使用 Foobar(类型 CustomType)作为类型字符串

您将如何修复 SomeFunction 以便它能够返回 Foobar (“somestring”) 的字符串值?

原文由 DaveUK 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.1k
2 个回答

值转换为字符串:

 func SomeFunction() string {
        return string(Foobar)
}

原文由 Cerise Limón 发布,翻译遵循 CC BY-SA 3.0 许可协议

最好为 --- 定义一个 String 函数 Customtype 随着时间的推移,它可以让你的生活更轻松 - 随着结构的发展,你可以更好地控制事物。如果你真的需要 SomeFunction 那么让它返回 Foobar.String()

    package main

    import (
        "fmt"
    )

    type CustomType string

    const (
        Foobar CustomType = "somestring"
    )

    func main() {
        fmt.Println("Hello, playground", Foobar)
        fmt.Printf("%s", Foobar)
        fmt.Println("\n\n")
        fmt.Println(SomeFunction())
    }

    func (c CustomType) String() string {
        fmt.Println("Executing String() for CustomType!")
        return string(c)
    }

    func SomeFunction() string {
        return Foobar.String()
    }

https://play.golang.org/p/jMKMcQjQj3

原文由 Ravi R 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题