英文:
How to convert a string to an array in Golang?
问题
如何在Go中有效地将字符串转换为只包含一个元素(即该字符串)的字符串数组。
例如:
var s string
s = "This is a string"
转换为
["This is a string"]
显然,一种方法是创建一个字符串数组,并将第一个元素初始化为该字符串,但我正在寻找一种更有效的方法。
英文:
How to convert a string to an array of strings with one element (i.e. that string) in Go effectively.
For example:
var s string
s = "This is a string"
to
["This is a string"]
Obviously, one way would be to make an array of strings and initialize the first element as that string but I am looking for an effective approach.
答案1
得分: 14
在Go语言中,要初始化一个字符串切片,你可以使用s := []string{"This is a string"}
。
要初始化一个字符串数组,你可以使用s := [1]string{"This is a string"}
。
唯一的区别在于是否指定数组的长度。
要了解你想要使用哪种结构,你应该阅读更多关于切片
和数组
之间的区别,可以在Go博客上阅读更多相关信息(https://blog.golang.org/go-slices-usage-and-internals)。
英文:
To initialize a string slice in Go, you use s := []string{"This is a string"}
.
To initialize a string array in Go, you use s := [1]string{"This is a string"}
.
The only difference (in declaring each) lies in specifying the array length or not.
To understand which structure you want to use, you should read more about the difference between slices
and arrays
on the Go Blog.
答案2
得分: 0
你可以阅读Go Blog上关于切片和数组的更多内容,以便理解。
英文:
intput:="This is a string"
output:=[]string{intput}
fmt.Println(intput)
fmt.Println(output)
To understand you should read more about slices and arrays on the Go Blog.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论