Go Standard Library Cookbook
上QQ阅读APP看书,第一时间看更新

How to do it...

  1. Open the console and create the folder chapter02/recipe04.
  2. Navigate to the directory.
  3. 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())
}
  1. Run the code by executing go run concat_buffer.go.
  2. See the output in the Terminal:
  1. Create the concat_copy.go file with the following content:
        package main

import (
"fmt"
)

func main() {

strings := []string{"This ", "is ", "even ",
"more ", "performant "}

bs := make([]byte, 100)
bl := 0

for _, val := range strings {
bl += copy(bs[bl:], []byte(val))
}

fmt.Println(string(bs[:]))

}
  1.  Run the code by executing go run concat_copy.go.
  2.  See the output in the Terminal: