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

huangapple go评论155阅读模式
英文:

How to convert interface{} to string?

问题

我正在使用docopt来解析命令行参数。这个方法是有效的,并且会生成一个类似下面的映射:

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

现在我想要将hostport的值连接成一个带有冒号的字符串。基本上,像这样:

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

不幸的是,这样做不起作用,我会得到错误消息:

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

显然,我需要将从映射中获取的值(它只是interface{}类型,可以是任何类型)转换为字符串。现在我的问题是,我该如何做到这一点?

英文:

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

map[&lt;host&gt;:www.google.de &lt;port&gt;: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[&quot;&lt;host&gt;&quot;] + &quot;:&quot; + arguments[&quot;&lt;port&gt;&quot;]

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

> invalid operation: arguments["<host>"] + ":" (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?

答案1

得分: 230

你需要添加type assertion .(string)。这是必要的,因为该映射的类型是map[string]interface{}

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

最新版本的Docopt返回一个Opts对象,该对象具有用于转换的方法:

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

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

host := arguments[&quot;&lt;host&gt;&quot;].(string) + &quot;:&quot; + arguments[&quot;&lt;port&gt;&quot;].(string)

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

host, err := arguments.String(&quot;&lt;host&gt;&quot;)
port, err := arguments.String(&quot;&lt;port&gt;&quot;)
host_port := host + &quot;:&quot; + port

答案2

得分: 112

你不需要使用类型断言,而是可以使用Sprintf函数和%v格式说明符:

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

这样就可以将<host><port>的值格式化为字符串,并用冒号连接起来。

英文:

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

hostAndPort := fmt.Sprintf(&quot;%v:%v&quot;, arguments[&quot;&lt;host&gt;&quot;], arguments[&quot;&lt;port&gt;&quot;])

答案3

得分: 26

根据Peter所说的进一步扩展:
由于你想要从interface{}转换为string,类型断言会导致麻烦,因为你需要考虑多种可能的输入类型。你需要对每种可能的类型进行断言,并在使用之前验证它是否是该类型。

使用fmt.Sprintf (https://golang.org/pkg/fmt/#Sprintf) 可以自动处理接口转换。由于你知道你期望的输出类型始终是字符串,Sprintf会处理接口背后的任何类型,而不需要你编写大量额外的代码。

英文:

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.

答案4

得分: 1

你也可以使用text/template

package main

import (
   "text/template"
   "strings"
)

func format(s string, v interface{}) string {
   t, b := new(template.Template), new(strings.Builder)
   template.Must(t.Parse(s)).Execute(b, v)
   return b.String()
}

func main() {
   m := map[string]interface{}{"<host>": "www.google.de", "<port>": "80"}
   s := format(`{{index . "<host>"}}:{{index . "<port>"}}`, m)
   println(s == "www.google.de:80")
}

https://pkg.go.dev/text/template

英文:

You could also use text/template:

package main

import (
   &quot;text/template&quot;
   &quot;strings&quot;
)

func format(s string, v interface{}) string {
   t, b := new(template.Template), new(strings.Builder)
   template.Must(t.Parse(s)).Execute(b, v)
   return b.String()
}

func main() {
   m := map[string]interface{}{&quot;&lt;host&gt;&quot;: &quot;www.google.de&quot;, &quot;&lt;port&gt;&quot;: &quot;80&quot;}
   s := format(`{{index . &quot;&lt;host&gt;&quot;}}:{{index . &quot;&lt;port&gt;&quot;}}`, m)
   println(s == &quot;www.google.de:80&quot;)
}

https://pkg.go.dev/text/template

huangapple
  • 本文由 发表于 2014年11月26日 05:58:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/27137521.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定