Reputation: 6947
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?
Upvotes: 3
Views: 1992
Reputation: 166529
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
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.
Upvotes: 6