如何在Go中创建一个项目的数组?

Kev*_*rke 2 go

假设一个函数接受一个字符串数组:

func Join(strs []string) {
     ...
}
Run Code Online (Sandbox Code Playgroud)

我有一个字符串:

a := "y'all ain't got the honey nut?"
Run Code Online (Sandbox Code Playgroud)

如何将该字符串转换为数组?

Kev*_*rke 9

您可以使用以下约定创建一个项目的切片:

a := "y'all ain't got the honey nut?"
singleItemArray := []string{a}

strings.Join(singleItemArray);
Run Code Online (Sandbox Code Playgroud)


Mos*_*afa 6

[]string{"string"}正如米尔顿布所说,问题的实际答案很简单.

但我想指出的是在Go中编写和使用可变参数函数是多么容易,Go是一个具有可变数量参数的函数.

您可以将功能的签名更改为F(a ...string).然后,a在功能片F,你可以这样调用它F("a")F("a", "b").而当你确实有一个片或数组,您可以通过调用传递到F F(a...).

不确定这种语法是否适合您的工作,但我想让您知道它作为一种选择.