Golang append string in string slice

huangapple go评论101阅读模式
英文:

Golang append string in string slice

问题

如何在字符串切片中追加字符串?
我尝试了以下代码:

s := make([]string, 1, 4)
s[0] = "filename"
s[0] := append(s[0], "dd")

但是这是错误的。然后我尝试了以下代码:

s[:1] := append(s[:1], "dd")

但是这也是错误的。

我该如何将一个字符串追加到s[0]中?

英文:

How to append string in a string 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]?

答案1

得分: 13

内置的append()函数用于将元素追加到切片中。如果你想将一个string追加到另一个string中,只需使用连接操作符+。如果你想将结果存储在索引为0的位置,只需将结果赋值给它:

s[0] = s[0] + "dd"

或者简写为:

s[0] += "dd"

注意,你不需要(也不能)使用:=这个短变量声明,因为你的s切片已经存在。

fmt.Println(s)的输出结果为:

[filenamedd]

如果你想将元素追加到切片而不是第一个元素,可以这样写:

s = append(s, "dd")

fmt.Println(s)的输出结果(继续上面的例子)为:

[filenamedd dd]

你可以在Go Playground上尝试这些代码。

英文:

The builtin append() function is for appending elements to a slice. If you want to append a string to a string, simply use the concatenation +. And if you want to store the result at the 0th index, simply assign the result to it:

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.

fmt.Println(s) output:

[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):

[filenamedd dd]

Try these on the Go Playground.

huangapple
  • 本文由 发表于 2015年6月29日 18:25:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/31113299.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定