I saw that range returns the key and the \"copy\" of the value. Is there a way for that range to return the adress of the item? Example
package main
import
It's been said in the comments already, but for those looking for answers right away, here's how you can achieve expected result by using a slice of pointers and by making the least changes to the original code.
package main
import "fmt"
type MyType struct {
field string
}
func main() {
// Slice of pointers instead of slice of type
var array [10]*MyType
// Initialize array manually
for idx := range array {
array[idx] = &MyType{}
}
for _, e := range array {
e.field = "foo"
}
for _, e := range array {
fmt.Println(e.field)
fmt.Println("--")
}
}
Here it is in playground
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("--")
}
}
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("--")
}
}