[英]Golang append string in string slice
How to append string in a string sclice? 如何在字符串sclice中附加字符串? I tried 我试过了
s := make([]string, 1, 4)
s[0] = "filename"
s[0] := append(s[0], "dd")
But it is not correct. 但这不正确。 Then I tried 然后我试了一下
s[:1] := append(s[:1], "dd")
But it is not correct either. 但它也不正确。
How can I append a string to s[0]
? 如何将字符串附加到s[0]
?
The builtin append()
function is for appending elements to a slice. 内置的append()
函数用于将元素附加到切片。 If you want to append a string
to a string
, simply use the concatenation +
. 如果要将string
附加到string
,只需使用串联+
。 And if you want to store the result at the 0th index, simply assign the result to it: 如果要将结果存储在第0个索引处,只需将结果分配给它:
s[0] = s[0] + "dd"
Or short: 或者简短:
s[0] += "dd"
Note also that you don't have to (can't) use :=
which is a short variable declaration , since your s
slice already exists. 另请注意,您不必(不能)使用:=
这是一个简短的变量声明 ,因为您s
切片已经存在。
fmt.Println(s)
output: fmt.Println(s)
输出:
[filenamedd]
If you want to append to the slice and not to the first element, then write: 如果要附加到切片而不是第一个元素,则写入:
s = append(s, "dd")
fmt.Println(s)
output (continuing the previous example): fmt.Println(s)
输出(继续上一个例子):
[filenamedd dd]
Try these on the Go Playground . 在Go Playground尝试这些。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.