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 copyingBuilder
is available from Golang version 1.10+The WriteString()
method accepts a string that needs to concatenate as a parameter.
The WriteString()
method doesn’t return anything, as it only modifies the original string.
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")
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())}
In the code snippet above:
s
with type as Builder
.WriteString()
to append the strings to s
.