Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range references instead values

I saw that range returns the key and the "copy" of the value. Is there a way for that range to return the address of the item? Example

package main

import "fmt"

type MyType struct {
    field string
}

func main() {
    var array [10]MyType

    for _, e := range array {
        e.field = "foo"
    }

    for _, e := range array {
        fmt.Println(e.field)
        fmt.Println("--")
    }
}

http://play.golang.org/p/AFOGG9NGpx

Here "field" is not modified because range sends the copy of field. Do I have to use index or is there any other way to modify the value?

like image 607
Epitouille Avatar asked Nov 25 '13 05:11

Epitouille


4 Answers

The short & direct answer: no, use the array index instead of the value

So the above code becomes:

package main

import "fmt"

type MyType struct {
    field string
}

func main() {
    var array [10]MyType

    for idx, _ := range array {
        array[idx].field = "foo"
    }

    for _, e := range array {
        fmt.Println(e.field)
        fmt.Println("--")
    }
}
like image 198
MushinNoShin Avatar answered Nov 10 '22 05:11

MushinNoShin


To combine @Dave C and @Sam Toliman's comments

package main

import "fmt"

type MyType struct {
    field string
}

func main() {
    var array [10]MyType

    for idx := range array {
        e := &array[idx]
        e.field = "foo"
    }

    for _, e := range array {
        fmt.Println(e.field)
        fmt.Println("--")
    }
}

https://play.golang.org/p/knKfziB1nce

like image 36
Sam Lee Avatar answered Nov 10 '22 07:11

Sam Lee


Go's range only supports assignment by value. There is no &range because the problem it solves is too trivial.

The desired effect can be achieved as follows:

for i := range array {
    e := &array[i]
    e.field = "foo"
}
like image 3
Grant Zvolsky Avatar answered Nov 10 '22 06:11

Grant Zvolsky


package main

import "fmt"

type MyType struct {
    field string
}

func main() {
    var array [10]MyType

    for index, _ := range array {
        array[index].field = "foo"
    }

    for _, e := range array {
        fmt.Println(e.field)
        fmt.Println("--")
    }
}
like image 2
Muhammad Fauzan Ady Avatar answered Nov 10 '22 06:11

Muhammad Fauzan Ady