In Go a rune
is a Unicode code point. Strings are encoded in UTF-8, and this means each character may be more than one byte
—and the rune
handles this. Rune is a 4-byte value like int32
.
Some string
methods (like those found in the "strings" package) require rune
arguments. And the for-range
loop over a string
returns a rune
as the second output value.
This program uses runes in a variety of ways. It uses a rune
as an argument, and also creates various local variables that have the rune
type.
rune
type by specifying the value "x" in single quotes. We can pass this to a method like ContainsRune
.string
, the for-range
syntax, and this returns a rune
as the second output value.TestRune
func
receives a value of rune
type. We test the rune
against a rune
literal in this method.rune
is an alias for the int32
type, so it is safe to convert back and forth from int32
with this type.package main import ( "fmt" "strings" ) func TestRune(x rune) bool { // Step 3: test a rune value. if x == 'c' { return true } return false } func main() { // Step 1: use rune literal, and pass rune literal to strings.ContainsRune. value := 'x' if strings.ContainsRune("abc_x", value) { fmt.Println("Contains rune", value) } // Step 2: use for-range loop over string, and use the second value which is a rune. word := "cat" for i, letter := range word { fmt.Println(i, letter, TestRune(letter)) } // Step 4: convert from int32 to rune. test := int32(100) testRune := rune(test) fmt.Println(test, testRune) }Contains rune 120 0 99 true 1 97 false 2 116 false 100 100
Runes are important as they can store values beyond ASCII—we can have accents and other characters. Constructs like the for-range
loop correctly handle these cases.