dfreire
dfreire

Reputation: 21

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

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?

Upvotes: 1

Views: 678

Answers (1)

Mr_Pink
Mr_Pink

Reputation: 109438

Convert the string to the correct type [conversions]

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

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

Upvotes: 5

Related Questions