![]() |
VOOZH | about |
In Go, strings are immutable sequences of bytes encoded with UTF-8. Concatenating two or more strings into a single string is straightforward in Go, and there are several ways to accomplish it. In this article,we will learn various ways to concatenate two strings in Golang.
Input:
s1 := "Hello, "
s2 := "Geeks!"
Output:
"Hello,Geeks!"
s1 + s2 #Using the "+" Operator
var b bytes.Buffer
b.WriteString(s1) # Usingbytes.BufferandWriteString()
b.WriteString(s2)
fmt.Sprintf("%s%s", s1, s2) # Usingfmt.Sprintf
s1 += s2 # Using the+=Operator (String Append)
strings.Join([]string{s1, s2}, "") # Usingstrings.Join
var builder strings.Builder
builder.WriteString(s1) # Usingstrings.BuilderandWriteString()
builder.WriteString(s2)
Table of Content
The + operator is the simplest way to concatenate strings in Go. This operator combines two or more strings.
s1 + s2Example:
Hello, Geeks!
bytes.Buffer and WriteString()The bytes.Buffer approach allows efficient string concatenation without generating intermediate strings, using WriteString() to append each segment.
var b bytes.Buffer
b.WriteString(s1)
b.WriteString(s2)
Example:
Hello, Geeks!
fmt.SprintfThe fmt.Sprintf function offers a formatted approach to string concatenation.
Syntax:
fmt.Sprintf("%s%s", s1, s2)Example:
Hello, Geeks!
+= Operator (String Append)In Go, you can append to an existing string using the += operator. This operation adds the second string to the end of the first.
s1 += s2Example
Hello, Geeks!
strings.JoinThe strings.Joinfunction can concatenate elements from a slice of strings with a specified separator. While it is most useful for multiple strings, it works well for pairs as well.
strings.Join([]string{s1, s2}, "")Example:
Hello, Geeks!
strings.Builder and WriteString()The strings.Builder type provides a similar approach to bytes.Buffer for efficient string concatenation with WriteString().
var builder strings.Builder
builder.WriteString(s1)
builder.WriteString(s2)
Example
Note:
The error
undefined: strings.Builderwill occur if your Go version is earlier than 1.10 because thestrings.Buildertype was introduced in Go 1.10. If your Go environment is set to a version earlier than 1.10,strings.Builderwill be undefined. To resolve this issue, make sure that your Go version is 1.10 or higher.