Building Strings

In Go, a string cannot be changed after it is made. You can read its bytes, but you cannot write to them. Try to change the first letter of a word, and the program does not compile:

package main

import "fmt"

func main() {
	word := "cat"
	word[0] = 'b'
	fmt.Println(word)
}

Output:

# command-line-arguments
./main.go:7:2: cannot assign to word[0] (neither addressable nor a map index expression)

Go says it cannot assign to word[0]. The bytes inside a string are read-only, and line 7 tries to write one.

This is why strings.ToUpper in the last lesson gave back a new string and left the old one as it was. To get a different text, you build a new string. You can then store it in the same variable:

word := "cat"
word = "b" + word[1:]
fmt.Println(word)

Output:

bat

word[1:] is the part of the string from index 1 to the end, the same slicing you used with slices. The new string "bat" replaces the old one in word.

Building a string in a loop

The simple way to build a long string is += in a loop:

line := ""
for i := 1; i <= 5; i++ {
	line += strconv.Itoa(i) + " "
}
fmt.Println("[" + line + "]")

Output:

[1 2 3 4 5 ]

The brackets show where the string starts and ends.

This works, but each += makes a whole new string and copies all the old text into it. With five parts, that does not matter. With thousands of parts, the program copies the same text again and again, and it gets slow.

strings.Builder

A strings.Builder collects the parts and makes the final string only once, at the end. You do not need make for it. A builder declared with var is empty and ready to use:

package main

import (
	"fmt"
	"strings"
)

func main() {
	var sb strings.Builder
	sb.WriteString("Hello")
	sb.WriteByte(',')
	sb.WriteRune(' ')
	sb.WriteString("Zoë")
	fmt.Println(sb.String())
	fmt.Println(sb.Len())
}

Output:

Hello, Zoë
11

You call these functions with the builder's name and a dot in front, like sb.WriteString(...). Functions called this way are methods, and the Methods lesson explains them. For now, read sb.WriteString("Hello") as "add Hello to the end of sb".

MethodWhat it does
WriteString(s)adds a string
WriteByte(b)adds one byte, like ','
WriteRune(r)adds one rune, like 'ë'
Len()gives the length so far, in bytes
String()gives the finished string

The length is 11, not 10, because ë takes two bytes.

Look back at the += loop: there is an extra space after the 5, before the ]. A common job is to put a separator between parts, but not after the last one. The trick is to write the separator before every part except the first:

var sb strings.Builder
for i := 1; i <= 5; i++ {
	if i > 1 {
		sb.WriteString(", ")
	}
	sb.WriteString(strconv.Itoa(i))
}
fmt.Println(sb.String())

Output:

1, 2, 3, 4, 5

fmt.Sprintf

You met fmt.Sprintf in the Formatted Output lesson. It gives the text back as a string instead of printing it. That makes it handy for building one part:

part := fmt.Sprintf("%s=%d", "pens", 12)
fmt.Println(part, len(part))

var sb strings.Builder
sb.WriteString(fmt.Sprintf("[%d]", 7))
fmt.Println(sb.String())

Output:

pens=12 7
[7]

In the exercise, use a strings.Builder to build one line from numbered words, with one space between the parts, then print the line and its length.