golang

Go’s String Builder (String Builder)

Strings are one of the most fundamental data types in Go and a lot of other programming languages. Strings allow us to store a sequence of characters.
In Go, we represent the strings as a sequence of strings enclosed in double quotes such as “Hello, World”.

Strings are immutable when it comes to Go. Hence, once we define a string, we cannot directly change its contents. To change the content, you need to create a new instance of a string with a modified content.

One thing you will notice in Go is that performing the string operations such as string concatenation can lead to performance issues. This is because we are creating a new string every time which can be very inefficient. Luckily, Go has a type called “strings.Builder” that can help in that regard.

In this tutorial, we will explore the ins and outs of this type and learn everything about it.

How Strings Work in Go

Before we jump into the string builder in Go, let us start by understanding how strings work in Go.

As we mentioned, strings are immutable. Hence, we create a new instance of the string during tasks such as concatenation.

str1 := "Hello, "
str2 := "World!"
result := str1 + str2

In this case, the given operation creates a new string to store the resulting “Hello, World!” string.

Golang Strings.Builder

The “strings.Builder” type in Go is part of the “strings” package and its role is to provide a better and efficient way of building and manipulating the strings without creating copies.

The “Builder” type comes with a lot of methods for string manipulation such as appending, inserting, modifying the strings, and more.

It uses a buffer to store the intermediate results which makes it more efficient when we need to build large strings or perform many string operations.

Strings Builder (Basic)

Let us start with the basics and discuss how to use the “Builder” type.

For us to use the “strings.Builder”, we need to create an instance using the “NewBuilder” function. An example is as follows:

package main
import (
    "fmt"
    "strings"
)
func main() {
    var builder strings.Builder    
}

We can also create a builder with an initial string content as follows:

builder := strings.NewBuilder("Hi")

String Builder Operations

Let us discuss the methods and operations that we can perform on the “Builder” type.

Appending the Strings
To append the strings to an instance of the “Builder” type, we can use the WriteString() method as shown in the following example:

package main
import (
    "fmt"
    "strings"
)

func main() {
    var builder strings.Builder
    builder.WriteString("https://")
    builder.WriteString("linuxhint.com")
    url := builder.String()
    fmt.Println(url)
}

In the given example, we start by creating an empty string builder. We then append two strings to it using the “WriteString” function.

Finally, we retrieve the concatenated string using the String() method and print it to the console as follows:

https://linuxhint.com

Clearing the Builder
We can clear the contents of a “strings.Builder” and reuse it by calling the “Reset” method as shown in the following example:

package main
import (
    "fmt"
    "strings"
)
func main() {
    var builder strings.Builder
    builder.WriteString("https://")
    fmt.Println(builder.String())
    builder.Reset()
    builder.WriteString("linuxhint.com")
    url := builder.String()

    fmt.Println(url)
}

In the given example, we start by creating a new Builder and append an https:// string into it.

We then use the Reset() function to clear the builder and make it ready for reuse. We do this by writing a new string into it which is “linuxhint.com”.

The resulting output is as follows:

https://
linuxhint.com

Using Byte Slices
In Go, strings are represented as byte slices under the hood. This is what makes the normal strings as read-only view to a sequence of bytes.

It is therefore no doubt that you will come across instances where you need to append the bytes slices to a string Builder.

For that, we can use the “Write” method as follows:

package main
import (
    "fmt"
    "strings"
)
func main() {
    var builder strings.Builder
    bytes := []byte("https://linuxhint.com")
    builder.Write(bytes)
    url := builder.String()
    fmt.Println(url)
}

There you have it!

Why Do You Need a String Builder?

You may be asking, why do I need a string builder? The short answer is you don’t. The normal string in Go is more than sufficient in a wide array of use cases.

However, one main advantage of using the Builder is the flexibility to build you a string with an added benefit of performance that is not present in a normal string.

Since it avoids unnecessary memory allocations and copying when building strings, it makes it more efficient than a simple string concatenation with the “+” operator.

Conclusion

In this tutorial, we learned most of the things that we need to know about the “Builder” type in Go. Unfortunately, it is not possible to discuss every feature of the “Builder” type in the scope of this tutorial. Hence, we recommended you to check the documentation for an added touch of information about the “Builder” type.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list