Rune and UTF-8
- Go course
- Beginner
- Lesson 61/90
- 4 min
Learn Unicode characters with rune and UTF-8 encoding.
Runes and UTF-8
In UTF-8 a character takes 1 to 4 bytes: a is 1, ç 2, € 3 and an emoji 4 bytes. To work at the character level use []rune and unicode/utf8:
s := "çay ☕"
fmt.Println(len(s)) // 8 bytes
fmt.Println(utf8.RuneCountInString(s)) // 5 characters
r := []rune(s)
fmt.Println(string(r[0])) // çThe unicode package
The unicode package classifies runes and recognizes Turkish letters correctly:
for _, r := range "Ğ5 a!" {
fmt.Println(string(r), unicode.IsLetter(r), unicode.IsDigit(r), unicode.IsUpper(r))
}Text analysis is done with functions such as unicode.IsSpace, unicode.IsPunct and unicode.ToUpper.
Practice Reverse it
Write the ters(s string) string function using []rune and print the result of ters("çiçek").
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func ters(s string) string {
r := []rune(s)
for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
r[i], r[j] = r[j], r[i]
}
return string(r)
}
func main() {
fmt.Println(ters("çiçek"))
}Expected output
keçiç
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why is <code>[]rune</code> used to reverse the text "çay"?
- It's shorter
- There is no difference
- Reversing bytes would break ç's two bytes Correct answer
- []byte isn't supported
Explanation: ç is two bytes; reversing at the byte level produces invalid UTF-8. Runes keep characters whole.
2 Count characters
n := utf8.____("ışık") // 4
n := utf8.RuneCountInString("ışık") // 4
Explanation: RuneCountInString gives the number of characters (runes) in a string.
3 Character and byte count
| Term | Meaning |
|---|---|
a |
1 byte |
ç |
2 bytes |
€ |
3 bytes |
😀 |
4 bytes |