Last updated on December 9, 2022
You can concatenate two or more strings by using the plus operator in Golang. We will learn it in this article. There is no package required to concatenate the strings, but we will need an fmt package that helps to print variables. So in your go file import fmt package.
import ("fmt")
Next, initialize two variables with different string values using var keyword.
var firstName string = "John"
var secondName string = "Smith"
To concatenate variables you need to use the plus operator. You can create a new variable fullName
and assign to it.
fullName := firstName + secondName
fmt.Println("fullName:", fullName)
// Output: JohnSmith
The fullName variable type is inferred which means the compiler analyzes the value and adds data type to the value.
You can also concatenate it without assigning the result to a new variable.
fmt.Println("Concatenated String:", firstName + secondName)
// Output: Concatenated String: JohnSmith
If you want to add some space between the strings then you need to add it. Below is the example,
fmt.Println("Concatenated String:", firstName + " " + secondName)
// Output: Concatenated String: John Smith
In the end, we are going to share the full code that is below.
package main
import ("fmt")
func main() {
var firstName string = "John"
var secondName string = "Smith"
fullName := firstName + secondName
fmt.Println("fullName:", fullName)
// Output: JohnSmith
fmt.Println("Concatenated String:", firstName + secondName)
// Output: JohnSmith
fmt.Println("Concatenated String:", firstName + " " + secondName)
// Output: John Smith
}