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"funcSlice2SliceOfPtr(slice []int) []*int {
n :=len(slice)
r :=make([]*int, n, n)
for i, s :=range slice {
r[i] = &s
}
return r
}
funcmain() {
x := []int{1, 2, 3}
y :=Slice2SliceOfPtr(x)
fmt.Println(x)
for _, yy :=range y {
fmt.Printf("%d ", *yy)
}
}
Before go1.22.0:
1
2
3
$ go run main.go
[12 3]333
In go1.22.0:
1
2
3
$ go run main.go
[12 3]123
Thank you for reading!
···
Love This Content?
Any kind of supports is greatly appreciated! Kindly support me via Bitcoin, Ko-fi, Trakteer, or just continue to read another content. You can write a response via Webmention and let me know the URL via Telegraph.