简体   繁体   English

如何在 Golang 中将字符串转换为数组?

[英]How to convert a string to an array in Golang?

How to convert a string to an array of strings with one element (ie that string) in Go effectively.如何在 Go 中有效地将字符串转换为具有一个元素(即该字符串)的字符串数组。

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

To initialize a string slice in Go, you use s := []string{"This is a string"} . 要在Go中初始化字符串切片,请使用s := []string{"This is a string"}
To initialize a string array in Go, you use s := [1]string{"This is a string"} . 要在Go中初始化字符串数组,请使用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 . 要了解您要使用哪种结构,您应该在Go Blog上阅读有关slicesarrays之间差异的更多信息。

intput:="This is a string"
output:=[]string{intput}
fmt.Println(intput)

fmt.Println(output) fmt.Println(输出)

To understand you should read more about slices and arrays on the Go Blog.要了解,您应该在 Go 博客上阅读有关切片和数组的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM