DEV Community

loading...

My Mistake On Converting Slice To Slice Of Ptr In Golang

clavinjune profile image Clavin June Originally published at clavinjune.dev on ・1 min read

Photo by @iavnt on Unsplash

I once made a function to convert a slice to slice of ptr and made a mistake.

My Function

func Slice2SliceOfPtr(slice []int) []*int {
    n := len(slice)
    r := make([]*int, n, n)

    for i, s := range slice {
        r[i] = &s
    }

    return r
}
Enter fullscreen mode Exit fullscreen mode

It seems normal to me until I realize something was wrong.

My Main Func

func main() {
    x := []int{1, 2, 3}
    y := Slice2SliceOfPtr(x)

    fmt.Println(x)

    for _, yy := range y {
        fmt.Printf("%d ", *yy)
    }
}
Enter fullscreen mode Exit fullscreen mode

Result

$ go run main.go 
[1 2 3]
3 3 3
Enter fullscreen mode Exit fullscreen mode

Why only the last element copied to the result?

Because the &s I used is mutated every iteration.

for i, s := range slice {
    r[i] = &s
}
Enter fullscreen mode Exit fullscreen mode

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

for i := range slice {
    r[i] = &slice[i]
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)

pic
Editor guide