[go] How to convert interface{} to string?

I'm using docopt to parse command-line arguments. This works, and it results in a map, such as

map[<host>:www.google.de <port>:80 --help:false --version:false]

Now I would like to concatenate the host and the port value to a string with a colon in-between the two values. Basically, something such as:

host := arguments["<host>"] + ":" + arguments["<port>"]

Unfortunately, this doesn't work, as I get the error message:

invalid operation: arguments[""] + ":" (mismatched types interface {} and string)

So obviously I need to convert the value that I get from the map (which is just interface{}, so it can be anything) to a string. Now my question is, how do I do that?

This question is related to go

The answer is


You don't need to use a type assertion, instead just use the %v format specifier with Sprintf:

hostAndPort := fmt.Sprintf("%v:%v", arguments["<host>"], arguments["<port>"])

To expand on what Peter said: Since you are looking to go from interface{} to string, type assertion will lead to headaches since you need to account for multiple incoming types. You'll have to assert each type possible and verify it is that type before using it.

Using fmt.Sprintf (https://golang.org/pkg/fmt/#Sprintf) automatically handles the interface conversion. Since you know your desired output type is always a string, Sprintf will handle whatever type is behind the interface without a bunch of extra code on your behalf.