WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Go · Advanced · question 49 of 100

Explain how to efficiently concatenate strings in Go.?

📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

In Go, strings are immutable, which means that concatenating strings using the ‘+‘ operator creates a new string every time a concatenation happens. This can lead to poor performance when concatenating a large number of strings, as it involves a lot of memory allocations and copies.

To efficiently concatenate strings in Go, it is recommended to use the ‘bytes.Buffer‘ or the ‘strings.Builder‘ types. Both of these types allow you to accumulate multiple strings while minimizing memory allocations and copying.

Here’s an example using ‘bytes.Buffer‘:

package main

import (
    "bytes"
    "fmt"
)

func main() {
    var buffer bytes.Buffer

    buffer.WriteString("Hello")
    buffer.WriteString(", ")
    buffer.WriteString("World")
    buffer.WriteString("!")

    result := buffer.String()
    fmt.Println(result) // Output: Hello, World!
}

And here’s an example using ‘strings.Builder‘ (introduced in Go 1.10):

package main

import (
    "fmt"
    "strings"
)

func main() {
    var builder strings.Builder

    builder.WriteString("Hello")
    builder.WriteString(", ")
    builder.WriteString("World")
    builder.WriteString("!")

    result := builder.String()
    fmt.Println(result) // Output: Hello, World!
}

Both of these types provide an efficient way to concatenate strings in Go, with ‘strings.Builder‘ being the more idiomatic and slightly more efficient option since it is optimized specifically for string concatenation. If you are using Go 1.10 or newer, it is recommended to use ‘strings.Builder‘.

In some cases, such as when you have a known and relatively small number of strings to concatenate, using the ‘strings.Join‘ function may also be efficient:

package main

import (
    "fmt"
    "strings"
)

func main() {
    parts := []string{"Hello", ", ", "World", "!"}
    result := strings.Join(parts, "")

    fmt.Println(result) // Output: Hello, World!
}

However, it is important to note that ‘strings.Join‘ requires all the strings to be concatenated to be stored in a slice. This can be less efficient if you are dealing with a dynamic or unknown number of strings, as it may involve additional memory allocations for creating the slice. In such cases, ‘bytes.Buffer‘ or ‘strings.Builder‘ are better options.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Go interview — then scores it.
📞 Practice Go — free 15 min
📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

All 100 Go questions · All topics