I have what is probably a general Golang question ...
# golang
s
I have what is probably a general Golang question (I'm a newbie). If I have a variable that defined as
interface{}
, how would I convert the value of that variable to a string?
i
If you’re sure the variable actually holds a string, you can cast it using
foo.(string)
https://play.golang.org/p/Cp3EAcdUeRn
If you want to test whether it’s string you can test it during assignment https://play.golang.org/p/chpYZVgNBKH
s
I'm sure it does contain a string, but
foo.(string)
(type assertion, I believe that's called?) doesn't work. Go gives a "panic: interface conversion" error.
i
yes type assertion is the correct Go term
s
Being more precise, the variable is actually defined as
[]interface{}
, but using
([]string)
doesn't work either.
i
ah you cannot, unfortunately, convert slices of interface{} to slices of another type in one step; you have to loop over each item in the slice and build a new slice of the type you want
s
Using a
range
statement to loop over it and convert each element?
i
right
s
However, if that variable is a field in a struct, then you can't use
range
on it, yes?
i
you can use range over any slice, wherever it is
s
Hmmm...OK. Thanks, this is very helpful!
i
y/w
You might also like the Gopher’s slack space https://invite.slack.golangbridge.org/
there’s ~50k people on that, and a #newbies channel as well
s
I'll go join, thanks!