Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
communitycreator

How to use string Builder in Golang

Gutha Vamsi Krishna

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())
}
Example for using String builder in Go

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.

RELATED TAGS

golang
communitycreator
RELATED COURSES

View all Courses

Keep Exploring