Strings Concatention In Go

development golang

In today’s snippet, let’s look at how to use string builder and bytes buffer to concatenate a list of strings. You can always use the + operator to concatenate strings, but it is memory inefficient just like in so many other languages. Each time + is used to concatenate a string, it allocates a new string in memory. This is because, like in most languages, strings in Go is immutable. To avoid this inefficiency, we can use Go’s strings.Builder and bytes.Buffer type. Let’s look at how we can use these types to concatenate strings.


package main

import (
	"bytes"
	"fmt"
	"strings"
)

func main() {
	// Using strings.Builder
	var sb strings.Builder
	words := []string{"welcome", "to", "strings", "concatenation", "tutorial"}
	for i, w := range words {
		sb.WriteString(w)
		if i < len(words)-1 {
			sb.WriteString(" ")
		}
	}
	fmt.Printf("Result: \"%s\"\n", sb.String())
	sb.Reset()

	// Using bytes.Buffer
	var bb bytes.Buffer
	for i, w := range words {
		bb.WriteString(w)
		if i < len(words)-1 {
			bb.WriteString(" ")
		}
	}
	fmt.Printf("Result: \"%s\"\n", bb.String())

	// Using strings.Join to concatenate a list of strings.
	result := strings.Join(words, " ")
	fmt.Printf("Result: \"%s\"\n", result)
}

Get new posts by email

Comments

comments powered by Disqus