How to concatenate strings in Go language

Contents

We can concatenate the strings using + operator in Go Language. The input string values should enclosed in the double quotes. Otherwise it will throw the error while concatenate the strings.

#1.String Concatenation in GO language

package main
import "fmt"

func main() {
	var A = "Revisit"
	fmt.Println(A)
	var B = "Class"
	fmt.Println(B)
    fmt.Println(A + " " + B)
}

Here we are concatenating the strings of A and B variables. The Println method is used to print the result of the strings. We have saved this program as string_concat.go and executing the program using go run command as below.

Ouput

$go run string_concat.go
Revisit
Class
Revisit Class

#2.Join a slices of strings into single string in Go

package main

import (
	"fmt"
	"strings"
	)
func main() {
    input := []string{"First","Second","Third"}
    // Join two strings
    output := strings.Join(input,"....")
    fmt.Println(output)
}

Here we have imported the strings package to implement the Join function in Go language. Join function is used to concatenates the elements of a string into a single string. The := syntax is shorthand for declaring and initializing a variable, e.g. input and output variables in this program.

Output

$go run string_join.go
First....Second....Third

#3.Append a strings to slice and join the same in Go

package main

import (
	"fmt"
	"strings"
	)

func main() {
	// Append two strings
    input := []string{}
    input = append(input, "Revisit")
    input = append(input, "Class")
	
	//Join the strings into single string
    output := strings.Join(input, "...")
    fmt.Println(output)
}

Go Language provide append function to append the new elements into a slice. Here the input variable contains all the elements of a slice. Then we have used Join function to concatenate the strings.

Output

$go run string_append.go
Revisit...Class