Reputation: 1455
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]
?
Upvotes: 3
Views: 25981
Reputation: 418695
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.
Upvotes: 13