Photo by @iavnt on Unsplash
Three years ago I wrote on how I wrongly implementing slice to slice pointer converter. It was not trivial for me, not really sure whether it is related to how Go implement their for loop.
I'm trying to patch the previous article since Go just released their latest version (1.22.0) and have changes on how the language itself implementing for loop, you can check it out here.
Now, if we try to implement our code from the last article using go1.22.0, we can see that the result is correct since they now no longer mutating the variable. The variable is not shared between each loop.
package main
import "fmt"
func Slice2SliceOfPtr(slice []int) []*int {
n := len(slice)
r := make([]*int, n, n)
for i, s := range slice {
r[i] = &s
}
return r
}
func main() {
x := []int{1, 2, 3}
y := Slice2SliceOfPtr(x)
fmt.Println(x)
for _, yy := range y {
fmt.Printf("%d ", *yy)
}
}
Before go1.22.0:
$ go run main.go
[1 2 3]
3 3 3
In go1.22.0:
$ go run main.go
[1 2 3]
1 2 3
Thank you for reading!
Top comments (0)