Golang String Concatenation
A string
is a sequence of one or more characters (letters, numbers, symbols) that can be either a constant or a variable. Check this out if you want to learn more about Strings in Go. In Go, string is an immutable chain of arbitrary bytes encoded with UTF-8 encoding format.
String concatenation is a way of joining two strings together to form a single string. There are several ways to concatenate strings in Go.
Method 1 : Golang Concat strings using + operator
This is the preferred method to concatenate strings in Go and the most obvious way to concatenate, where we use the +
operator to concat 2 strings str1
and str2
.
// Method 1 : Concatenate strings using + operator
package main
import "fmt"
func main() {
var str1 string
str1 = "Debug"
var str2 string
str2 = "Pointer"
// Concatenate two strings
// Using + operator
fmt.Println("Concatenated String- ", str1 + str2)
str3:= "Debug"
str4:= "is Fun"
// Concatenate two strings and a string inbetween
// Using + operator
result:= str3 + "ing " + str4
fmt.Println("Concatenated String- ", result)
}
Output of the program-
Concatenated String- DebugPointer
Concatenated String- Debuging is Fun
Program exited.
Method 2 : Golang Concat strings using fmt.Sprintf
You can use fmt.Sprintf
to concatenate strings while formatting it as well. Check out the spaces that is available only where it is intented to. You can also format your messages with pre-defined text as well.
// Method 2 : Concatenate strings using + operator
package main
import "fmt"
func main() {
str1 := "Welcome"
str2 := "to"
str3 := "Debug"
str4 := "Pointer"
// Concatenate multiple strings using
// Sprintf() function
result := fmt.Sprintf("Hello! %s %s %s%s", str1,
str2, str3, str4)
fmt.Println(result)
}
Output of the program-
Hello! Welcome to DebugPointer
Program exited.
Method 3 : Golang Concat Strings using += operator
Similar to most other programming languages, the s1 += s2
operator is a shorthand operator for s1 = s1 + s2
. Since +
is used to concat strings, this method works. Here is a detailed example-
// Method 3 : Concatenate strings using += operator
package main
import "fmt"
func main() {
str1 := "Debug"
str2 := "Pointer"
// Using += operator
str1 += str2
fmt.Println("String: ", str1)
str1 += " Hope you enjoy coding"
fmt.Println("String: ", str1)
}
String: DebugPointer
String: DebugPointer Hope you enjoy coding
Program exited.
Method 4 : Using bytes.Buffer, and buffer.String() to Concat Strings in Golang
Obviously this method is not something that is common in most programs, but, strings can be concatenated like this in Golang.
// Method 1 : Concatenate strings using + operator
package main
import (
"bytes"
"fmt"
)
func main() {
// Using bytes.Buffer with
// WriteString() function
var b bytes.Buffer
b.WriteString("h")
b.WriteString("e")
b.WriteString("l")
b.WriteString("l")
b.WriteString("o")
fmt.Println("String: ", b.String())
}
String: hello
Program exited.