Learn Strings in Go

A Go string is an immutable row of UTF-8 bytes. Double quotes process escapes like \n, backticks are a raw string literal that takes everything as it is. +…

The till at Bimo's Meatball Stall allows names of at most 5 letters on a receipt, and it checks the length with len. Then André comes in, and his name is refused: Go says it is 6 long. Yet it has only five letters.

The cause is how Go stores a string, the type for text. A Go string is a row of bytes, pieces of data 8 bits in size, written with the UTF-8 rules, and what it holds can't be changed once it is made (immutable). Think of the stall's order name board as built from stick-on letter tiles. A plain letter like A takes one tile. An accented letter like é takes two tiles, and a Japanese character takes three. Go's len function counts tiles, not letters.

Making and joining strings

name := "André"
order := "tendon meatballs, iced tea"
fmt.Println(name + " orders " + order)

notes := `C:\stall\menu.txt`
fmt.Println(notes)
André orders tendon meatballs, iced tea
C:\stall\menu.txt

The strings package

The strings package holds functions for working with text. Each function returns a new string, the original stays as it is.

order := "tendon meatballs, iced tea"
fmt.Println(strings.ToUpper(order))                               // TENDON MEATBALLS, ICED TEA
fmt.Println(len(order))                                           // 26
fmt.Println(strings.Contains(order, "tea"))                       // true
fmt.Println(strings.Replace(order, "iced tea", "iced orange", 1)) // tendon meatballs, iced orange
fmt.Println(strings.Split(order, ", "))                           // [tendon meatballs iced tea]
fmt.Println(strings.TrimSpace("  tendon meatballs  "))            // tendon meatballs

fmt.Sprintf: putting text together

fmt.Sprintf works like Printf, but its result is returned as a string, not printed. Good for putting a line of the receipt together:

receipt := fmt.Sprintf("%s orders %d portions", name, 3)
fmt.Println(receipt) // André orders 3 portions

For a receipt built line by line inside a loop, += makes a new string and copies everything in it on every round. The strings package has two tools for that:

menu := []string{"tendon meatballs", "chicken noodles", "iced tea"}
fmt.Println(strings.Join(menu, ", "))

var b strings.Builder
for i, m := range menu {
	fmt.Fprintf(&b, "%d. %s\n", i+1, m)
}
fmt.Print(b.String())
tendon meatballs, chicken noodles, iced tea
1. tendon meatballs
2. chicken noodles
3. iced tea
Way When to pick it
+ Two or three pieces of text.
fmt.Sprintf Text with numbers or formatting, like the receipt line above.
strings.Join Everything in a slice, with the same separator between items.
strings.Builder Text put together bit by bit inside a loop.

Bytes and runes

The letter é is stored in 2 bytes, so len("André") gives 6, not 5. That is why the till refused André's name. One whole character is called a rune: the rune type (another name for int32) holds the Unicode number of one character, and it is written in single quotes, like 'é'.

package main

import (
	"fmt"
	"unicode/utf8"
)

func main() {
	name := "André"
	fmt.Println(len(name))                    // 6
	fmt.Println(utf8.RuneCountInString(name)) // 5
	fmt.Println(name[0], name[4])             // 65 195
	for i, r := range name {
		fmt.Printf("%d:%c ", i, r)
	}
	fmt.Println()
}
6
5
65 195
0:A 1:n 2:d 3:r 4:é

⚠️ Letters you can't swap and numbers that turn into letters

TL;DR: A Go string is an immutable row of UTF-8 bytes. Double quotes process escapes like \n, backticks are a raw string literal that takes everything as it is. + joins strings, and a number is converted first with strconv.Itoa or fmt.Sprintf. The strings package: ToUpper, Contains, Replace(s, old, new, n), Split, TrimSpace, and all of them return a new string. fmt.Sprintf returns formatted text without printing it. len counts bytes: len("André") = 6, len("hålö") = 6. Count letters with utf8.RuneCountInString, and for i, r := range gives whole runes.

⚡ Double quotes or backticks

Write:

notes := `C:\stall\menu.txt`
fmt.Println(notes) // C:\stall\menu.txt

Meaning: Text between backticks is a raw string literal: every character is taken as it is, \ is not processed. Between double quotes, \n becomes a new line.

⚡ strings functions make a new string

Write:

order := "tendon meatballs, iced tea"
fmt.Println(strings.ToUpper(order))         // TENDON MEATBALLS, ICED TEA
fmt.Println(strings.Contains(order, "tea")) // true

Meaning: Each strings function returns a new string, the original stays as it is. + joins strings, but a number is converted first with strconv.Itoa.

⚡ len counts bytes

Guess first: André has 5 letters. What does len("André") give?

6. é is stored in 2 bytes, and len counts bytes, not letters. Count the letters with utf8.RuneCountInString.

Meaning: A Go string is a row of UTF-8 bytes. for i, r := range reads it rune by rune.

What you will learn