How to Concatenate Strings in Go

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.


Concatenating strings is a fundamental operation that is often required in different programming tasks. So, if you’re looking to learn how to concatenate strings in Golang, you’re in the right place.

Before diving into the code examples, let’s first understand the theory behind concatenating strings in Golang.

What does it mean to Concatenate a String?

Concatenating strings in Golang involves combining two or more strings into a single string. Golang provides a built-in function called “concat” for concatenating strings. The concat function takes two or more strings and returns a single string that is the result of combining all the input strings.

Here’s how it works:

package main

import "fmt"

func main() {
    str1 := "Hello"
    str2 := "World"
    result := str1 + " " + str2
    fmt.Println(result)
}

In the code above, we declare two string variables called “str1” and “str2”. We then use the “+” operator to concatenate the two strings and a space in between them. The resulting string is stored in a variable called “result”. We then use the fmt.Println() function to print the value of “result”.

Another way to concatenate strings in Golang is by using the “strings” package. The “strings” package provides many useful functions for manipulating strings, including the “Join” function, which can be used to concatenate multiple strings.

Here’s an example:

package main

import "fmt"
import "strings"

func main() {
    str := []string{"Hello", "World"}
    result := strings.Join(str, " ")
    fmt.Println(result)
}

In the code above, we declare a string slice called “str” with two elements. We then use the “Join” function from the “strings” package to concatenate the elements of the slice with a space in between them. The resulting string is stored in a variable called “result”. We then use the fmt.Println() function to print the value of “result”.

So why would someone want to concatenate strings in Golang? One common use case is when working with user input or database data that needs to be combined into a single string. By concatenating the strings, you can create a complete message or value that can be processed by your program.

In conclusion, concatenating strings in Golang is a fundamental operation that you’ll encounter frequently in your Golang programming journey. By using the “+” operator or the “Join” function from the “strings” package, you can easily concatenate strings and manipulate text data.

I hope you found this tutorial helpful. If you have any questions or comments, please feel free to leave them below.



Stay up to date on the latest in Coding for AI and Data Science

Intuit Mailchimp