String concatenation

February 9, 2024

Today we’re looking at a deceptively short section of the spec: String concatenation…

String concatenation

Strings can be concatenated using the + operator or the += assignment operator:

s := "hi" + string(c)
s += " and good bye"

String addition creates a new string by concatenating the operands.

That’s it.

Short, and sweet, eh?

Except that it’s not quite so sweet, when you consider the implications of the last sentence: Every time you use + or += for a string, you create a new string. This is because strings in Go are immutable.

x := "Hello"
x = "world" // Creates a new string, discarding the old one, to be cleaned up by the Garbage Collector

This means that if you’re coming from a lanugage like PHP, JavaScript, or Perl, where it’s common to build strings incrementally, you could be inadvertently wasting a lot of memory and stressing your garbage collector.

message := "Hello, " + name
message += "Thank you for using my amazing app!"
message += "Here at " + companyName + " we take your patronage seriously!"
message += "On the other hand, we ignore the memory consumption of our"
message += "application."

That’s what not to do. 😉 Every instance of message += discards the old (ever larger) value of the string, and allocates memory for the new version.

Depending on your exact situation, there are a number of alternatives. Check out this StackOverflow post for a number of alternatives, but a good general purpose one is the strings.Builder type in the standard library. It makes the code a bit more verbose, but much more efficient:

var b strings.Builder
b.WriteString("Hello, " + name)
b.WriteString("Thank you for using my amazing app!")
b.WriteString("Here at " + companyName + " we take your patronage seriously!")
b.WriteString("We also care about  the memory consumption of our")

message := b.String()

Quotes from The Go Programming Language Specification Version of August 2, 2023

Share this

Direct to your inbox, daily. I respect your privacy .

Unsure? Browse the archive .