You can't write into a
strings in Go are immutable.
The best alternatives are the
bytes.Buffer and since Go 1.10 the faster
strings.Builder types: they implement
io.Writer so you can write into them, and you can obtain their content as a
Builder.String(), or as a byte slice with
You can also have a
string as the initial content of the buffer if you create the buffer with
s := "Hello" buf := bytes.NewBufferString(s) fmt.Fprint(buf, ", World!") fmt.Println(buf.String())
Output (try it on the Go Playground):
s2 := "to be appended" buf.WriteString(s2)
Also note that if you just want to concatenate 2
strings, you don't need to create a buffer and use
fmt.Fprintf(), you can simply use the
+ operator to concatenate them:
s := "Hello" s2 := ", World!" s3 := s + s2 // "Hello, World!"
It may also be of interest: What's the difference between ResponseWriter.Write and io.WriteString?