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.
Builderminimizes memory copyingBuilderis 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 packagesimport("fmt""strings")//program execution starts herefunc main(){//declare variablevar s strings.Builder//append string Hellos.WriteString("Hello")//append string froms.WriteString(" from")//append string educatives.WriteString(" educative")//Convert string builder to string and print itfmt.Println(s.String())}
Explanation
In the code snippet above:
- Line 13: We declare a variable
swith type asBuilder. - Lines 16, 19, and 22: We use
WriteString()to append the strings tos. - Line 25: We convert the string builder to string and display/print it.