Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert interface{} to string?

Tags:

go

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?

like image 951
Golo Roden Avatar asked Nov 25 '14 21:11

Golo Roden


People also ask

What is [] interface {} Golang?

interface{} means you can put value of any type, including your own custom type. All types in Go satisfy an empty interface ( interface{} is an empty interface). In your example, Msg field can have value of any type.

How do you implement an interface in go?

Implementing an interface in Go To implement an interface, you just need to implement all the methods declared in the interface. Unlike other languages like Java, you don't need to explicitly specify that a type implements an interface using something like an implements keyword.

What is type assertion in Golang?

Type assertions in Golang provide access to the exact type of variable of an interface. If already the data type is present in the interface, then it will retrieve the actual data type value held by the interface. A type assertion takes an interface value and extracts from it a value of the specified explicit type.


2 Answers

You need to add type assertion .(string). It is necessary because the map is of type map[string]interface{}:

host := arguments["<host>"].(string) + ":" + arguments["<port>"].(string) 

Latest version of Docopt returns Opts object that has methods for conversion:

host, err := arguments.String("<host>") port, err := arguments.String("<port>") host_port := host + ":" + port 
like image 69
Grzegorz Żur Avatar answered Oct 24 '22 14:10

Grzegorz Żur


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>"]) 
like image 36
Peter Stace Avatar answered Oct 24 '22 13:10

Peter Stace