Iterating through multi dimensional array in Go

huangapple go评论78阅读模式
英文:

Iterating through multi dimensional array in Go

问题

在下面的代码示例中:

var a [3][5]int8
for _, h := range a {
    for _, cell := range h {
        fmt.Print(cell, " ")
    }
    fmt.Println()
}

在每次迭代中,h 是否是 a 的一行的副本?也就是说,h 是否包含 a 的一行的副本,还是 h 获取了对它的引用?

英文:

In the following code example

var a [3][5]int8
for _, h := range a {
    for _, cell := range h {
        fmt.Print(cell, " ")
    }
    fmt.Println()
}

is the copy of a row of a made in every iteration? i.e., does h contain a copy of a row of a or does h get a reference to it?

答案1

得分: 6

一个示例代码如下:

package main

import "fmt"

func main() {
	var a [3][5]int8
	fmt.Println(a)
	for _, h := range a {
		h = [5]int8{1, 2, 3, 4, 5}
		for _, cell := range h {
			fmt.Print(cell, " ")
		}
		fmt.Println()
	}
	fmt.Println(a)
}

输出结果:

[[0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0]]
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
[[0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0]]

这段代码使用了Go语言中的range关键字来遍历一个二维数组a。在每次迭代中,将迭代的值赋给对应的迭代变量h,然后执行相应的代码块。输出结果显示了数组的初始值和经过赋值后的结果。

你可以参考Go语言规范中的For语句部分了解更多关于range关键字的用法。

英文:

A copy. For example,

package main

import "fmt"

func main() {
	var a [3][5]int8
	fmt.Println(a)
	for _, h := range a {
		h = [5]int8{1, 2, 3, 4, 5}
		for _, cell := range h {
			fmt.Print(cell, " ")
		}
		fmt.Println()
	}
	fmt.Println(a)

}

Output:

[[0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0]]
1 2 3 4 5 
1 2 3 4 5 
1 2 3 4 5 
[[0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0]]

> The Go Programming Language Specification
>
> For statements
>
> A "for" statement with a "range" clause iterates through all entries
> of an array, slice, string or map, or values received on a channel.
> For each entry it assigns iteration values to corresponding iteration
> variables and then executes the block.
>
> The iteration values are assigned to the respective iteration
> variables as in an assignment statement.

huangapple
  • 本文由 发表于 2014年10月15日 18:53:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/26380753.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定