How to Concatenate string type data in golang
In Go, you can concatenate strings using the +
operator. Here's an example:
str1 := "Hello, "
str2 := "world!"
result := str1 + str2
fmt.Println(result) // "Hello, world!"
You can also use the +=
operator to append one string to another:
str1 := "Hello, "
str2 := "world!"
str1 += str2
fmt.Println(str1) // "Hello, world!"
Another way to concatenate strings is using the strings.Join
function from the strings
package, which takes a slice of strings as an argument and returns a concatenated string separated by a given separator:
words := []string{"Hello,", "world!"}
result := strings.Join(words, " ")
fmt.Println(result) // "Hello, world!"
If you want to concatenate multiple strings frequently, using bytes.Buffer is a more efficient way:
var buffer bytes.Buffer
buffer.WriteString("Hello, ")
buffer.WriteString("world!")
result := buffer.String()
fmt.Println(result) // "Hello, world!"
This creates an empty buffer and then appends strings to it. The WriteString
function is more efficient than repeated concatenation because it does not need to allocate a new string for each concatenation. Instead, it maintains an internal byte slice and a growing capacity.