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?
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("--")
}
}
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
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"
}
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("--")
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With