byte and rune
- Go course
- Beginner
- Lesson 21/90
- 4 min
Learn byte and rune types and character representation.
byte and rune
Go strings are made of UTF-8 bytes. A byte (uint8) represents a single byte and a rune (int32) a single Unicode character. English letters are 1 byte, but letters such as ğ, ş, ü are 2 bytes.
s := "ağ"
fmt.Println(len(s)) // 3 (bytes)
fmt.Println(len([]rune(s))) // 2 (characters)Walking characters with range
for i, r := range s walks a string character by character; i is the character's byte position and r the rune value. Indexing with s[i] gives a single byte and splits multi-byte letters.
for i, r := range "gö" {
fmt.Println(i, string(r))
}
// 0 g
// 1 öSingle quotes ('a') make a rune constant.
Practice Bytes and characters
Declare s := "Gölge". Print the byte count (len(s)) and the character count (len([]rune(s))) on one line.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
s := "Gölge"
fmt.Println(len(s), len([]rune(s)))
}Expected output
6 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>len("çay")</code> return?
- 6
- 2
- 4 Correct answer
- 3
Explanation: len counts bytes: ç is 2 bytes, a and y one each → 4. For the character count use utf8.RuneCountInString or len([]rune(s)).
2 Character count
n := len([]____("ışık")) // 4
n := len([]rune("ışık")) // 4
Explanation: Converting to []rune first makes len give the character count.
3 Type and meaning
| Term | Meaning |
|---|---|
byte |
A single byte (uint8) |
rune |
A Unicode character (int32) |
'a' |
A rune constant |
"a" |
A string |