How to initialize a type with an underlying string value in go?

huangapple go评论77阅读模式
英文:

How to initialize a type with an underlying string value in go?

问题

这个可以工作:

type T string
var t T = "hello"

http://play.golang.org/p/275jQ4ixvp

但是这个会报错 cannot use s (type string) as type T in assignment(无法将类型为 string 的 s 分配给类型为 T 的 t)

type T string
s := "world"
var t T = s

http://play.golang.org/p/vm3mC5ltcE

我该如何使第二种情况工作?

英文:

This works:

type T string
var t T = "hello"

http://play.golang.org/p/275jQ4ixvp

But this fails with cannot use s (type string) as type T in assignment

type T string
s := "world"
var t T = s

http://play.golang.org/p/vm3mC5ltcE

How can I make this second situation work?

答案1

得分: 5

将字符串转换为正确的类型[转换]

http://play.golang.org/p/dkavI_QgPb

s := "world"
t := T(s)
fmt.Println(t)

英文:

Convert the string to the correct type [conversions]

http://play.golang.org/p/dkavI_QgPb

s := "world"
t := T(s)
fmt.Println(t)

huangapple
  • 本文由 发表于 2014年11月13日 00:20:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/26891629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定