Go:字符串到数组字符串

Har*_*pta 0 arrays string go slice

如何有效地将字符串转换为Go中的一个元素(即该字符串)的字符串数组.

例如:

var s string
s = "This is a string"
Run Code Online (Sandbox Code Playgroud)

["This is a string"]
Run Code Online (Sandbox Code Playgroud)

显然,一种方法是创建一个字符串数组并将第一个元素初始化为该字符串,但我正在寻找一种有效的方法.

Car*_*ann 7

要在Go中初始化字符串切片,请使用s := []string{"This is a string"}.
要在Go中初始化字符串数组,请使用s := [1]string{"This is a string"}.

唯一的区别(声明每个)在于指定数组长度与否.

要了解您要使用哪种结构,您应该阅读有关Go博客之间slices和之间差异的更多信息.arrays