DEV Community

Clavin June
Clavin June

Posted on • Originally published at clavinjune.dev on

3 3

My Mistake On Converting Slice To Slice Of Ptr In Golang

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay