简体   繁体   English

如何将interface {}转换为字符串?

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

I'm using docopt to parse command-line arguments. 我正在使用docopt来解析命令行参数。 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. 现在我想将hostport值连接到一个字符串,在这两个值之间加上冒号。 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) 无效操作:arguments [“”] +“:”(不匹配的类型interface {}和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. 所以显然我需要将我从地图中获得的值(只是interface{} ,因此它可以是任何东西)转换为字符串。 Now my question is, how do I do that? 现在我的问题是,我该怎么做?

You need to add type assertion .(string) . 您需要添加类型断言 .(string) It is necessary because the map is of type map[string]interface{} : 这是必要的,因为地图的类型为map[string]interface{}

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

Latest version of Docopt returns Opts object that has methods for conversion: Docopt的最新版本返回选择采用具有用于转换方法的对象:

host, err := arguments.String("<host>")
port, err := arguments.String("<port>")
host_port := host + ":" + port

您不需要使用类型断言,而只需在Sprintf使用%v格式说明符:

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. 为了扩展Peter所说的内容:由于您希望从接口{}转到字符串,因此键入断言会导致令人头疼,因为您需要考虑多个传入类型。 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. 使用fmt.Sprintf( https://golang.org/pkg/fmt/#Sprintf )自动处理接口转换。 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. 由于您知道所需的输出类型始终是字符串,因此Sprintf将处理接口背后的任何类型,而无需代表您使用大量额外代码。

Now i was created package for converting interface to any data type here the github link and godoc link https://github.com/mufti1/interconv 现在我创建了用于将接口转换为任何数据类型的包,这里是github链接和godoc链接https://github.com/mufti1/interconv

godoc link https://godoc.org/github.com/mufti1/interconv/package godoc链接https://godoc.org/github.com/mufti1/interconv/package

you just import from godoc and then call the function 你只需从godoc导入然后调用该函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM