Go Wiki:範圍子句
規格:https://go.dev.org.tw/ref/spec#For_statements
摘要
範圍子句提供一種方法來迭代陣列、區段、字串、對應或通道。
範例
for k, v := range myMap {
log.Printf("key=%v, value=%v", k, v)
}
for v := range myChannel {
log.Printf("value=%v", v)
}
for i, v := range myArray {
log.Printf("array value at [%d]=%v", i, v)
}
參考
如果在範圍運算式的左側只使用一個值,則它是此表格中的第 1 個值。
範圍運算式 | 第 1 個值 | 第 2 個值(選用) | 註解 |
---|---|---|---|
陣列或區段 a [n]E 、*[n]E 或 []E |
索引 i int |
a[i] E |
|
字串 s 字串類型 | 索引 i int |
符號 int |
範圍會迭代 Unicode 碼點,而不是位元組 |
對應 m map[K]V |
金鑰 k K |
值 m[k] V |
|
通道 c chan E | 元素 e E |
無 |
陷阱
在迭代值區段或對應時,可能會嘗試這樣做
items := make([]map[int]int, 10)
for _, item := range items {
item = make(map[int]int, 1) // Oops! item is only a copy of the slice element.
item[1] = 2 // This 'item' will be lost on the next iteration.
}
make
和指定看起來像可以運作,但 range
的值屬性(在此儲存為 item
)是 items
中值的 *副本*,而不是指向 items
中值的指標。下列程式碼會運作
items := make([]map[int]int, 10)
for i := range items {
items[i] = make(map[int]int, 1)
items[i][1] = 2
}
此內容是 Go Wiki 的一部分。