Go strings store text, and runes represent individual Unicode characters.

rune A `rune` is an alias for `int32` and commonly represents one Unicode character.

Strings and Runes

word
strings_runes.go
Replay: real traced execution (multi-file project)
package main

import "fmt"

func main() {
	var word = "Go"
	firstRune := []rune(word)[0]
	message := word + " types"

	fmt.Println("word=", word)
	fmt.Println("first=", string(firstRune))
	fmt.Println("message=", message)
}
package main

import "fmt"

func main() {
	var word = "Ruby"
	firstRune := []rune(word)[0]
	message := word + " types"

	fmt.Println("word=", word)
	fmt.Println("first=", string(firstRune))
	fmt.Println("message=", message)
}
package main

import "fmt"

func main() {
	var word = "Data"
	firstRune := []rune(word)[0]
	message := word + " types"

	fmt.Println("word=", word)
	fmt.Println("first=", string(firstRune))
	fmt.Println("message=", message)
}
  1. word ← "Go", firstRune ← 71, message ← "Go types"

    5func main() {6  var word→ "Go" = "Go" //@word="Ruby", "Data"7  firstRune→ 71 := []rune(word"Go")[0]8  message→ "Go types" := word"Go" + " types"910  fmt.Println("word=", word"Go")11  fmt.Println("first=", string(firstRune71))12  fmt.Println("message=", message"Go types")13}
    outputword= Go
    first= G
    message= Go types
  1. word ← "Ruby", firstRune ← 82, message ← "Ruby types"

    5func main() {6  var word→ "Ruby" = "Ruby"7  firstRune→ 82 := []rune(word"Ruby")[0]8  message→ "Ruby types" := word"Ruby" + " types"910  fmt.Println("word=", word"Ruby")11  fmt.Println("first=", string(firstRune82))12  fmt.Println("message=", message"Ruby types")13}
    outputword= Ruby
    first= R
    message= Ruby types
  1. word ← "Data", firstRune ← 68, message ← "Data types"

    5func main() {6  var word→ "Data" = "Data"7  firstRune→ 68 := []rune(word"Data")[0]8  message→ "Data types" := word"Data" + " types"910  fmt.Println("word=", word"Data")11  fmt.Println("first=", string(firstRune68))12  fmt.Println("message=", message"Data types")13}
    outputword= Data
    first= D
    message= Data types

Follow the Text

  1. word starts as Go.
  2. []rune(word)[0] reads the first rune, G.
  3. message := word + " types" becomes Go types.
  4. The program prints word= Go, first= G, and message= Go types. | word | first rune | message | | --- | --- | --- | | Go | G | Go types | | Ruby | R | Ruby types | | Data | D | Data types |

Exercise: strings_runes.go

Reproduce first= G and message= Go types, then use the pinned words Ruby and Data to predict each first rune.