How to Concatenate Strings in Golang

Hey! If you love Go and building Go apps as much as I do, let's connect on Twitter or LinkedIn. I talk about this stuff all the time!

Want to learn how to build better Go applications faster and easier? You can.

Check out my course on the Go Standard Library. You can check it out now for free.


Hello, fellow Go programmers! Today, we’re going to explore the world of string concatenation in Go. String concatenation is the process of combining two or more strings into a single string, and it’s an essential operation in many programs. In this article, we’ll show you how to concatenate strings in Go and explore some of the best practices for working with strings. So, let’s get started!

First, let’s start with the basics. In Go, we can concatenate strings using the + operator, like so:

str1 := "Hello, "
str2 := "world!"
result := str1 + str2
fmt.Println(result)

This code defines two string variables, str1 and str2, and concatenates them using the + operator. We then use the fmt package’s Println() function to print the result to the console.

But what if we need to concatenate more than two strings? No problem! We can chain multiple + operators together, like so:

str1 := "Hello, "
str2 := "my "
str3 := "name "
str4 := "is "
str5 := "Fred."
result := str1 + str2 + str3 + str4 + str5
fmt.Println(result)

This code defines five string variables and concatenates them into a single string using multiple + operators. We then use the fmt package’s Println() function to print the result to the console.

But that’s not all! Golang also provides a built-in strings.Join() function that we can use to concatenate strings. Here’s an example:

strs := []string{"Hello,", "my", "name", "is", "Fred."}
result := strings.Join(strs, " ")
fmt.Println(result)

This code defines a slice of strings called strs and uses the strings.Join() function to concatenate them into a single string with spaces between each word. We then use the fmt package’s Println() function to print the result to the console.

Conclusion

String concatenation is a fundamental operation in many programs, and Golang provides powerful tools for working with strings. With the syntax and functions we’ve explored in this article, you’ll be able to concatenate strings in Golang with ease. So, let’s get concatenating with Golang!


Questions or comments? Reach out to me


Learn how to leverage the Go Standard Library like a PRO.

I just created a new course, The Go Standard Library, check it out!