英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论