Golang: Iterate Slice

By Xah Lee. Date: .

Iterate Slice or Array

for i, v := range slice {body}

iterate slice, where i is current index and v the value.

If a variable is not used, name it _ to stop compiler from complaining. e.g. for _, v := range slice {body}. The _ is called blank identifier.

package main

import "fmt"

func main() {
	var s = []int{9, 2, 8, 61}
	for i, x := range s {
		fmt.Println(i, x)
	}
}

// 0 9
// 1 2
// 2 8
// 3 61

Golang, array and slice