https://pulumi.com logo
#golang
Title
# golang
s

salmon-account-74572

09/24/2020, 10:09 PM
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

important-appointment-55126

09/24/2020, 10:20 PM
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

salmon-account-74572

09/24/2020, 10:22 PM
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

important-appointment-55126

09/24/2020, 10:22 PM
yes type assertion is the correct Go term
s

salmon-account-74572

09/24/2020, 10:23 PM
Being more precise, the variable is actually defined as
[]interface{}
, but using
([]string)
doesn't work either.
i

important-appointment-55126

09/24/2020, 10:24 PM
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

salmon-account-74572

09/24/2020, 10:26 PM
Using a
range
statement to loop over it and convert each element?
i

important-appointment-55126

09/24/2020, 10:26 PM
right
s

salmon-account-74572

09/24/2020, 10:27 PM
However, if that variable is a field in a struct, then you can't use
range
on it, yes?
i

important-appointment-55126

09/24/2020, 10:28 PM
you can use range over any slice, wherever it is
s

salmon-account-74572

09/24/2020, 10:28 PM
Hmmm...OK. Thanks, this is very helpful!
i

important-appointment-55126

09/24/2020, 10:29 PM
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

salmon-account-74572

09/24/2020, 10:46 PM
I'll go join, thanks!
3 Views