How to use string Builder in Golang

Overview

In this shot, we will learn to use a string builder in Golang.

String Builder is used to efficiently concatenate strings in Golang.

  • Builder minimizes memory copying
  • Builder is available from Golang version 1.10+

Parameters

The WriteString() method accepts a string that needs to concatenate as a parameter.

Return value

The WriteString() method doesn’t return anything, as it only modifies the original string.

Syntax

We need to declare the variable and provide the type as strings.Builder, and then we can use the WriteString() method to append the string as follows:

var str strings.Builder
str.WriteString("provide string here")

Example

In the following example, we will use Builder to build a string Hello from educative:

package main
//import packages
import(
"fmt"
"strings"
)
//program execution starts here
func main(){
//declare variable
var s strings.Builder
//append string Hello
s.WriteString("Hello")
//append string from
s.WriteString(" from")
//append string educative
s.WriteString(" educative")
//Convert string builder to string and print it
fmt.Println(s.String())
}

Explanation

In the code snippet above:

  • Line 13: We declare a variable s with type as Builder.
  • Lines 16, 19, and 22: We use WriteString() to append the strings to s.
  • Line 25: We convert the string builder to string and display/print it.

Free Resources