for range
Golang 基礎: for range 迴圈
Categories:
列印陣列
僅用到陣列 value
數值
nums := []int{2, 3, 4}
sum := 0
for _, value := range nums {
sum += value
}
fmt.Println("sum:", sum)
列印陣列 key
及 value
var name_list = []string{`Golang`, `Python`, `PHP`}
for key, value := range name_list {
fmt.Printf("language key: %d = %s\n", key, value)
}
// language key: 0 = Golang
// language key: 1 = Python
// language key: 2 = PHP
arr1 := [3][2]int{{1, 2}, {3, 4}, {5, 6}}
fmt.Println(arr1) // [[1 2] [3 4] [5 6]]
for key, value := range arr1 {
fmt.Printf("%d => %d\n", key, value)
}
// 0 => [1 2]
// 1 => [3 4]
// 2 => [5 6]