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
- Text between double quotes
"..."may hold escape sequences, codes that start with\:\nis a new line,\ta tab,\"a quote. - Text between backticks
`...`is a raw string literal: every character is taken as it is,\is not processed, and it may run over several lines. Good for Windows paths, regex, or JSON. +joins two strings into a new string.- A string can't be joined to a number.
"Portions: " + portionswithportions := 3fails withinvalid operation: "Portions: " + portions (mismatched types untyped string and int). Convert the number first withstrconv.Itoa(portions), or usefmt.Sprintf.
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
strings.ToUpper(s)turns every letter into a capital,strings.ToLower(s)does the opposite.len(s)is a built-in function, not part ofstrings, and it counts bytes. Text made only of plain letters (ASCII) has as many bytes as letters:"tendon meatballs, iced tea"has 26, spaces and the comma included.strings.Contains(s, "tea")answerstruewhensholds"tea".strings.Replace(s, old, new, n)replaces the firstnmatches.n= 1 is only the first,n= -1 is all of them (the same asstrings.ReplaceAll).strings.Splitcuts text into parts,strings.TrimSpacedrops spaces at the start and end.
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:é
utf8.RuneCountInString(name)counts the letters, giving 5. Another way:len([]rune(name)).name[4]takes byte 4, not letter 4:195, the first tile ofé.for i, r := range nameloops rune by rune.iis the byte position where that letter starts,ris the letter. Noticeéstarts at position 4 and there is no position 5: the two tiles are read as one letter. The details offorcome in the for lesson later.%cprints a rune as a character. Another example:"hålö"has 4 letters, but itslenis 6.
⚠️ Letters you can't swap and numbers that turn into letters
- Changing one letter in a string.
name[0] = 'a'fails withcannot assign to name[0] (neither addressable nor a map index expression). Strings are immutable, so make a new string, for example withstrings.Replace. string(number)to turn a number into text.string(65)gives"A", the character with number 65, not"65". Usestrconv.Itoa(65).go vet(whichgo testalso runs for you) catches it:conversion from untyped int to string yields a string of one rune, not a string of digits.- Single quotes for text.
'André'fails withmore than one character in rune literal. Single quotes are only for one rune. - Forgetting
ninstrings.Replace. Withn= 1, only the first match is replaced.
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.