Member-only story
Go Language Learning Notes — Common Keywords
I. for and range
Go language provides two loop structures for
loop and for... range
loop.
For... range
complete data iteration, support string, array, array pointer, slice, dictionary, channel type, return index, key-value data.
1. Classic Loop and Range Loop
- Classic loops: Use the
for
keyword and conditional statements to control how the loop works. - Range Loop: Range loop is a way to iterate over iterable data structures using the
for range
keyword. Range loop supports string, array, array pointer, slice, dictionary, channel type, and returns index and key-value data.
2. For range
does not appear cyclic perpetual motion machine
func main() {
arr := []int{1, 2, 3}
for _, v := range arr {
arr = append(arr, v)
}
fmt.Println(arr)
}
// 1 2 3 1 2 3
For range
when traversing an array or slice, it will first copy the array or slice to an intermediate variable ha
. Copying occurs during the assignment process, so the slice we traverse is not the original slice variable, so there will be no looping perpetual motion machine.
3. For k, v: = range
, the variable v
is reused in each iteration
The variable v
used in the loop will be overwritten by reassignment at each iteration, and copying will be triggered…