Concatenation is the process of joining two or more strings together to form a new single string in Go strings. The + operator is the simplest way to concatenate two or more strings in the Go language.
We’ll discuss a number of ways to concatenate strings in golang. The string consists of an immutable chain of arbitrary bytes encoded in UTF-8.
Method 1: Using + Operator
Let’s concatenate string using ‘+’ operator.
package main
import "fmt"
func main() {
// Creating and initializing strings using var keyword
var str1 string
str1 = "Welcome! "
var str2 string
str2 = "golanglearn"
// Concatenating strings using + operator
fmt.Println("Concatenated string: ", str1+str2)
}
Output:
Concatenated string: Welcome! golanglearn
Method 2: Using bytes.Buffer
We can also create a string by concatenating the bytes of the strings using bytes. Buffer with WriteString() method.it doesn’t generate a new string as like ‘+’ operator.
package main
import (
"bytes"
"fmt"
)
func main() {
// Creating and initializing strings
var st bytes.Buffer
st.WriteString("g")
st.WriteString("o")
st.WriteString("l")
st.WriteString("a")
st.WriteString("n")
st.WriteString("g")
fmt.Println("String 1: ", st.String())
st.WriteString("l")
st.WriteString("e")
st.WriteString("r")
st.WriteString("n")
fmt.Println("Concatenated: ", st.String())
}
Output:
String 1: golang Concatenated: golanglern
Method 3: Using Sprintf
We can also concatenate string using Sprintf() method.
import "fmt"
func main() {
// Creating and initializing strings
str1 := "golang"
str2 := "learn"
// Concatenating strings using
// Sprintf() function
result := fmt.Sprintf("%s%s", str1, str2)
fmt.Println(result)
}
Output:
golanglearn
Method 3: Using Join
The Join() method is part of the string package. This combines all of the items in a string slice into a single string.
Syntax:
func Join(str []string, sep string) string
Where:
str – The string slices.
sep – This is placed between the elements in the final string.
package main
import (
"fmt"
"strings"
)
func main() {
// Creating and initializing slice of string
myslice := []string{"Hello", "golang",
"learn"}
// Using join() function
result := strings.Join(myslice, "-")
fmt.Println(result)
}
Output:
Hello-golang-learn
