3

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
  • It depends if you're using arrays or a slices. Commented Oct 15, 2014 at 11:01

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

1 Comment

That's the good answer, but if he's using slices, in the first loop the data itself should not be copied (and it's the same for range on a map).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.