Dav*_*eUK 15 string type-conversion go
在这个奇怪的例子中,有人创建了一个新类型,它实际上只是一个字符串:
type CustomType string
const (
Foobar CustomType = "somestring"
)
func SomeFunction() string {
return Foobar
}
Run Code Online (Sandbox Code Playgroud)
但是,此代码无法编译:
不能在返回参数中使用Foobar(类型CustomType)作为类型字符串
你如何修复SomeFunction,以便它能够返回Foobar("somestring")的字符串值?
Cer*_*món 25
func SomeFunction() string {
return string(Foobar)
}
Run Code Online (Sandbox Code Playgroud)
Rav*_*avi 21
最好为以下定义一个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()
}
Run Code Online (Sandbox Code Playgroud)
https://play.golang.org/p/jMKMcQjQj3
Kri*_* PC 10
对于每个类型 T,都有一个相应的转换操作 T(x),将值 x 转换为类型 T。如果两者具有相同的基础类型,或者两者都是指向的未命名指针类型,则允许从一种类型到另一种类型的转换。相同基础类型的变量;这些转换会更改类型,但不会更改值的表示形式。如果 x 可分配给 T,则允许进行转换,但通常是多余的。- 摘自The Go 编程语言 - 作者:Alan AA Donovan
根据您的示例,这里有一些将返回值的不同示例。
package main
import "fmt"
type CustomType string
const (
Foobar CustomType = "somestring"
)
func SomeFunction() CustomType {
return Foobar
}
func SomeOtherFunction() string {
return string(Foobar)
}
func SomeOtherFunction2() CustomType {
return CustomType("somestring") // Here value is a static string.
}
func main() {
fmt.Println(SomeFunction())
fmt.Println(SomeOtherFunction())
fmt.Println(SomeOtherFunction2())
}
Run Code Online (Sandbox Code Playgroud)
它将输出:
somestring
somestring
somestring
Run Code Online (Sandbox Code Playgroud)