Essential Go range statement  Suggest an edit

range over a slice

There are 3 variants of iterating over a slice with range.

Get both index and element:

a := []int{3, 15, 8}
for idx, el := range a {
	fmt.Printf("idx: %d, element: %d\n", idx, el)
}
idx: 0, element: 3
idx: 1, element: 15
idx: 2, element: 8

Get only index:

a := []int{3, 15, 8}
for idx := range a {
	fmt.Printf("idx: %d\n", idx)
}
idx: 0
idx: 1
idx: 2

Get only element:

a := []int{3, 15, 8}
for _, el := range a {
	fmt.Printf("element: %d\n", el)
}
element: 3
element: 15
element: 8

  ↑ ↓ to navigate     ↵ to select     Esc to close