Member-only story

Go Language Learning Notes — Common Keywords

Beck Moulton
7 min readJul 5, 2024

--

I. for and range

Go language provides two loop structures forloop and for... rangeloop.

For... rangecomplete 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 forkeyword 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 rangekeyword. Range loop supports string, array, array pointer, slice, dictionary, channel type, and returns index and key-value data.

2. For rangedoes 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 rangewhen 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 vis reused in each iteration

The variable vused in the loop will be overwritten by reassignment at each iteration, and copying will be triggered…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet