Concatenating a string with writer
Besides the built-in +
operator, there are more ways to concatenate the string. This recipe will describe the more performant way of concatenating strings with the bytes
package and the built-in copy
function.
How to do it...
- Open the console and create the folder
chapter02/recipe04
. - Navigate to the directory.
- Create the
concat_buffer.go
file with the following content:
package main import ( "bytes" "fmt" ) func main() { strings := []string{"This ", "is ", "even ", "more ", "performant "} buffer := bytes.Buffer{} for _, val := range strings { buffer.WriteString(val) } fmt.Println(buffer.String()) }
- Run the code by executing
go run concat_buffer.go
. - See the output in the Terminal:

- Create the
concat_copy.go
file with the following content:
package main import ( "fmt" ) func...