Home
Go
rune: Return rune, string for-range
Updated Jan 10, 2025
Dot Net Perls
Rune. 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.
for
Example. 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.
Step 1 We create a local variable of rune type by specifying the value "x" in single quotes. We can pass this to a method like ContainsRune.
strings.Contains
Step 2 We use the idiomatic Go syntax for looping over a string, the for-range syntax, and this returns a rune as the second output value.
Step 3 The TestRune func receives a value of rune type. We test the rune against a rune literal in this method.
func
Step 4 A 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
Summary. 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.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Jan 10, 2025 (new).
Home
Changes
© 2007-2025 Sam Allen