A rune is Go's name for a Unicode code point, an alias for int32. The unicode and unicode/utf8 packages classify, convert, and decode them.
Examples
A rune is an alias for int32, one Unicode code point. string(r) re-encodes it back to UTF-8; converting a string to []rune decodes it the other way.
r := 'A'
fmt.Printf("%c %d %U\n", r, r, r)
s := string(r)
fmt.Println(s)
runes := []rune("héllo")
fmt.Println(len(runes), len("héllo"))Output
A 65 U+0041
A
5 6The unicode package classifies a rune by its Unicode category. range over a string already yields decoded runes, so no manual UTF-8 handling is needed here.
for _, r := range "Go 123!" {
switch {
case unicode.IsLetter(r):
fmt.Printf("%c: letter\n", r)
case unicode.IsDigit(r):
fmt.Printf("%c: digit\n", r)
case unicode.IsSpace(r):
fmt.Printf("%c: space\n", r)
default:
fmt.Printf("%c: other\n", r)
}
}Output
G: letter
o: letter
: space
1: digit
2: digit
3: digit
!: otherunicode.ToUpper and ToLower work rune by rune; strings.ToUpper is built on top of them for a whole string at once.
r := 'a'
fmt.Println(string(unicode.ToUpper(r)))
s := "Go gopher"
fmt.Println(strings.ToUpper(s))
for _, r := range "aB3" {
fmt.Printf("%c -> %c\n", r, unicode.ToUpper(r))
}Output
A
GO GOPHER
a -> A
B -> B
3 -> 3len(s) counts bytes; utf8.RuneCountInString counts decoded runes. DecodeRuneInString gives direct access to the same decoding range uses internally.
s := "héllo"
fmt.Println(len(s), utf8.RuneCountInString(s))
r, size := utf8.DecodeRuneInString(s[1:])
fmt.Printf("%c %d\n", r, size)
fmt.Println(utf8.ValidRune(r))Output
6 5
é 2
true| Function | Description |
|---|---|
string(r) string('A') | Converts a single rune to its one-character string |
[]rune(s) []rune("héllo") | Decodes a string into its sequence of runes |
unicode.IsLetter(r) unicode.IsLetter('G') | Reports whether r is a letter |
unicode.IsDigit(r) unicode.IsDigit('3') | Reports whether r is a decimal digit |
unicode.IsSpace(r) unicode.IsSpace(' ') | Reports whether r is a space, tab, newline, or similar |
unicode.IsPunct(r) unicode.IsPunct('!') | Reports whether r is a punctuation character |
unicode.IsUpper(r) / IsLower(r) unicode.IsUpper('A') | Reports whether r is upper- or lowercase |
unicode.ToUpper(r) / ToLower(r) unicode.ToUpper('a') | Returns the upper- or lowercase form of r |
utf8.RuneLen(r) utf8.RuneLen('é') | Number of bytes r takes when UTF-8 encoded |
utf8.ValidRune(r) utf8.ValidRune(r) | Reports whether r is a valid Unicode code point |
utf8.RuneCountInString(s) utf8.RuneCountInString("héllo") | Number of runes in s, as opposed to bytes |
utf8.DecodeRuneInString(s) r, size := utf8.DecodeRuneInString(s) | Decodes the first rune in s, returning it and its byte width |
Related: Strings unicode unicode/utf8