4

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 Answer 1

13

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.