golang 将“type []string”转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41756412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:36:16  来源:igfitidea点击:

golang convert "type []string" to string

stringgotypesstring-concatenation

提问by user3888307

I'm sure this is a simple question, but I keep bumping into this. I see others are as well.

我确定这是一个简单的问题,但我一直在碰到这个问题。我看别人也是。

I see some people create a forloop and run through the slice as to create a string, is there an easier way to convert a []stringto a string?

我看到有些人创建一个for循环并运行切片以创建一个字符串,是否有更简单的方法将 a 转换[]string为 a string

Will sprintfdo it?

sprintf做吗?

回答by Tom Regner

You can use strings.Join(arr []string, seperator string) string, as in pretty much any other language I know

您可以使用strings.Join(arr []string, seperator string) string,就像我知道的几乎任何其他语言一样

https://golang.org/pkg/strings/#Join

https://golang.org/pkg/strings/#Join

回答by HubertS

this is simple example, which You can paste to main function:

这是一个简单的示例,您可以将其粘贴到主函数中:

  stringArray := []string {"Hello","world","!"}
  justString := strings.Join(stringArray," ")
  fmt.Println(justString)

And link to working exampleon playground.

并链接到操场上的工作示例

Or using very simple function simple function

或者使用非常简单的函数 simple function

回答by Somo S.

Will Sprintdo it?

Yes indeed!

Sprint做吗?

确实是的!

Here is another way to convert to a string if all you care about is that it is a string and not specifically how it looks (see answers above with strings.Joinfor a little more flexibility).

这是另一种转换为字符串的方法,如果您只关心它是一个字符串而不是它的具体外观(请参阅上面的答案以strings.Join获得更大的灵活性)。

The advantage of this method (or variations such as Sprintf), is it will work with (almost) every other data such as mapsand structsand any custom type that implements the fmt.Stringerinteface.

这种方法(或诸如 的变体Sprintf)的优点是它可以(几乎)与所有其他数据一起使用,例如mapsstructs以及实现该fmt.Stringer接口的任何自定义类型。

  stringArray := []string {"Hello","world","!"}
  justString := fmt.Sprint(stringArray)

Here is a link to a working example.

这是一个工作示例的链接。