Lesson Introduction and Overview

Hello, aspiring developers! Today, we're going to delve into a crucial concept in Go: Concatenation Operations. Concatenation is all about joining strings together. We'll start by explaining what concatenation is, and then we will explore various ways to perform it in Go. Armed with this essential knowledge, we'll conclude with some helpful tips to bypass common stumbling blocks.

Understanding Concatenation

Concatenation acts like glue, binding strings together to craft meaningful sentences. Suppose you have two strings — "Neil" and "Armstrong". We can link them to form a single string, "Neil Armstrong". Let's look at how:

firstName := "Neil"
lastName := "Armstrong"
fullName := firstName + " " + lastName   // Concatenation operation

fmt.Println(fullName)  // Output: Neil Armstrong

Here, the '+' operator attaches firstName, a space, and lastName, forming the fullName string. Simple, isn't it? You might have observed this technique in some of our earlier fmt.Println statements.

String Concatenation with '+' Operator in Go

In Go, the '+' operator only allows the same data types specifically when concatenation is intended. Let's dig deeper with an example:

name := "Alice"
apples := 5
message := name + " has " + strconv.Itoa(apples) + " apples."  // Explicit conversion of 'int' to 'string'

fmt.Println(message)  // Output: Alice has 5 apples.

Pay close attention, as Go does not implicitly convert the integer apples to a string. We used strconv.Itoa for explicit conversion before performing the concatenation.

Journey with `strings.Builder` in Go

In Go, the string object is immutable. You can't modify it directly once it's created. However, Go does provide efficient ways to modify strings. The strings.Builder is your friend when it comes to concatenating strings. It concatenates strings efficiently, without creating new objects with each operation.

First of all, let's import "string" to get the access to the strings.Builder:

import (
    "fmt"
    "strings"
)

Now, let's see it in action:

var sb strings.Builder
sb.WriteString("Hello, ")
sb.WriteString("World!")
sb.WriteString(" What ")
sb.WriteString("a wonderful ")
sb.WriteString("day out there!")
fmt.Println(sb.String())  // Output: Hello, World! What a wonderful day out there!

Do you see how we first created a strings.Builder, then used WriteString to add strings to it? The final combined string is produced with sb.String().

strings.Builder provides a more efficient way to concatenate large amounts of strings than the '+' operator does. It's an excellent choice for efficient and versatile string manipulation!

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal