snippetgoCritical
How to convert interface{} to string?
Viewed 0 times
stringconverthowinterface
Problem
I'm using docopt to parse command-line arguments. This works, and it results in a map, such as
Now I would like to concatenate the
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
map[:www.google.de :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[""] + ":" + arguments[""]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?Solution
You need to add type assertion
Latest version of Docopt returns Opts object that has methods for conversion:
.(string). It is necessary because the map is of type map[string]interface{}:host := arguments[""].(string) + ":" + arguments[""].(string)Latest version of Docopt returns Opts object that has methods for conversion:
host, err := arguments.String("")
port, err := arguments.String("")
host_port := host + ":" + portCode Snippets
host := arguments["<host>"].(string) + ":" + arguments["<port>"].(string)host, err := arguments.String("<host>")
port, err := arguments.String("<port>")
host_port := host + ":" + portContext
Stack Overflow Q#27137521, score: 254
Revisions (0)
No revisions yet.