← Back to course: Go from scratch

Operators, strings and runes

Video coming soon

With variables under control, it is time to do things with them. Operators are the symbols that combine values: they add, compare, negate. In Go there are few and they are very predictable. This lesson also explains something that surprises people coming from other languages: how Go handles text. A string is not a list of letters, it is a sequence of bytes in UTF-8, and understanding that difference avoids bugs with accents, the letter ñ, emojis and non-Latin alphabets.

Arithmetic, comparison and logical operators

The arithmetic ones are +, -, *, / and % (remainder of the division). Beware of integer division: 7 / 2 gives 3, because the result is another integer; to get 3.5 at least one operand must be a decimal. The comparison ones are ==, !=, <, <=, > and >=, and they return a bool. The logical ones are && (and), || (or) and ! (not), with short-circuit evaluation: if the first operand of && is false, the second is not even evaluated. To modify a variable there are the shorthand forms +=, -=, *= and /=, and the increments x++ and x--, which in Go are statements, not expressions.

go
package main

import "fmt"

func main() {
	a, b := 7, 2
	fmt.Println(a/b, a%b)               // 3 1
	fmt.Println(float64(a) / float64(b)) // 3.5

	age := 20
	isAdult := age >= 18 && age < 65
	fmt.Println(isAdult, !isAdult) // true false

	counter := 10
	counter += 5
	counter++
	fmt.Println(counter) // 16
}

Strings: bytes and runes

A string is written between double quotes, or between backticks for literal text that can span several lines. It is immutable: you cannot change a character, only create a new string. The len function returns the number of bytes, not characters. In UTF-8, English letters take one byte, but an ñ or an accent takes two, and an emoji can take four. If you index with s[0] you get a byte, not a letter. To work with characters use the rune type, which represents a Unicode code point, and walk the text with for range, which decodes the runes for you.

go
package main

import (
	"fmt"
	"strings"
	"unicode/utf8"
)

func main() {
	s := "año"
	fmt.Println(len(s))                    // 4 bytes
	fmt.Println(utf8.RuneCountInString(s)) // 3 runes

	for i, r := range s {
		fmt.Println(i, string(r)) // 0 a, 1 ñ, 3 o
	}

	r := []rune(s)
	fmt.Println(string(r[1])) // ñ

	fmt.Println(strings.ToUpper("go"), strings.Contains("gopher", "ph"))
	fmt.Println("go" + "lang") // concatenation
}

The strings package

The standard library includes the strings package with functions for almost everything: ToUpper and ToLower change case, TrimSpace removes spaces at the ends, Split divides a text by a separator, Join joins a list, Replace substitutes, Contains and HasPrefix query. Remember that, since strings are immutable, these functions return a new string and do not modify the original. A frequent mistake is calling strings.ToUpper(s) and forgetting to store the result in a variable.

  • len(s) counts bytes; utf8.RuneCountInString(s) counts characters.
  • s[i] gives a byte; for range gives runes.
  • A literal with single quotes like 'a' is a rune, not a string.
  • Strings are compared with == and ordered with <.

✎ My notes

Saved only in this browser. Sign in to keep it in your account.0/5000 characters

← PreviousNext →