I once made a function to convert a slice to slice of ptr and made a mistake.
My Function
1
2
3
4
5
6
7
8
9
10
func Slice2SliceOfPtr(slice []int) []*int {
n := len(slice)
r := make([]*int, n, n)
for i, s := range slice {
r[i] = &s
}
return r
}
It seems normal to me until I realize something was wrong.
My Main Func
1
2
3
4
5
6
7
8
9
10
func main() {
x := []int{1, 2, 3}
y := Slice2SliceOfPtr(x)
fmt.Println(x)
for _, yy := range y {
fmt.Printf("%d ", *yy)
}
}
Result
1
2
3
$ go run main.go
[1 2 3]
3 3 3
Why only the last element copied to the result?
Because the &s I used is mutated every iteration.
1
2
3
for i, s := range slice {
r[i] = &s
}
s never created as a new variable on every iteration, but its value is mutated inside the for loop
So I changed the iteration like this:
Better One
1
2
3
for i := range slice {
r[i] = &slice[i]
}
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.