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
1 2 3 4 5 6 7 8 9 10 |
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
1 2 3 4 |
$go run string_concat.go Revisit Class Revisit Class |
#2.Join a slices of strings into single string in Go
1 2 3 4 5 6 7 8 9 10 11 12 |
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
1 2 |
$go run string_join.go First....Second....Third |
#3.Append a strings to slice and join the same in Go
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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
1 2 |
$go run string_append.go Revisit...Class |