range statement:
range statement
suggest changeIterate over a string
s := "Hey 世界"
for i, r := range s {
fmt.Printf("idx: %d, rune: %d\n", i, r)
}
idx: 0, rune: 72
idx: 1, rune: 101
idx: 2, rune: 121
idx: 3, rune: 32
idx: 4, rune: 19990
idx: 7, rune: 30028
Notice that range assumes that string is UTF-8 encoded and iterates over Unicode characters (runes), not bytes of the string.
First returned value i is byte index of the rune in the string, not Unicode character index.
To iterate over characters, use byte indexes:
s := "a 世"
for i := 0; i < len(s); i++ {
c := s[i]
fmt.Printf("idx: %d, byte: %d\n", i, c)
}
idx: 0, byte: 97
idx: 1, byte: 32
idx: 2, byte: 228
idx: 3, byte: 184
idx: 4, byte: 150
Iterate over a slice
a := []int{3, 15, 8}
for i, el := range a {
fmt.Printf("idx: %d, element: %d\n", i, el)
}
idx: 0, element: 3
idx: 1, element: 15
idx: 2, element: 8
Iterate over a map
m := map[string]int{
"three": 3,
"five": 5,
}
for key, value := range m {
fmt.Printf("key: %s, value: %d\n", key, value)
}
key: three, value: 3
key: five, value: 5
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents
4
Strings
5
Pointers
6
Arrays
7
Slices
8
Maps
9
Structs
10
Interfaces
14
range statement
15
Functions
16
Methods
18
Defer
20
Concurrency
22
Mutex
23
Packages
27
Logging
30
JSON
31
XML
32
CSV
33
YAML
34
SQL
35
HTTP Client
36
HTTP Server
38
Reflection
39
Context
40
Package fmt
41
OS Signals
42
Testing
49
gob
50
Plugin
53
Console I/O
54
Cryptography
59
Contributors