How to Concatenate string type data in golang

Budiaramdhan Rindi
1 min readJan 11, 2023

--

In Go, you can concatenate strings using the + operator. Here's an example:

str1 := "Hello, "
str2 := "world!"
result := str1 + str2
fmt.Println(result) // "Hello, world!"

You can also use the += operator to append one string to another:

str1 := "Hello, "
str2 := "world!"
str1 += str2
fmt.Println(str1) // "Hello, world!"

Another way to concatenate strings is using the strings.Join function from the strings package, which takes a slice of strings as an argument and returns a concatenated string separated by a given separator:

words := []string{"Hello,", "world!"}
result := strings.Join(words, " ")
fmt.Println(result) // "Hello, world!"

If you want to concatenate multiple strings frequently, using bytes.Buffer is a more efficient way:

var buffer bytes.Buffer
buffer.WriteString("Hello, ")
buffer.WriteString("world!")
result := buffer.String()
fmt.Println(result) // "Hello, world!"

This creates an empty buffer and then appends strings to it. The WriteString function is more efficient than repeated concatenation because it does not need to allocate a new string for each concatenation. Instead, it maintains an internal byte slice and a growing capacity.

--

--

Budiaramdhan Rindi
Budiaramdhan Rindi

Written by Budiaramdhan Rindi

Currently work as Coder since 2011 and still have to learn. Dota 2 and Football Manager are the games I still play to stay fresh.