DEV Community

Clavin June
Clavin June

Posted on • Originally published at clavinjune.dev on

Update on My Mistake on Converting Slice to Slice of Ptr in Golang

Photo by @iavnt on Unsplash

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)
    }
}
Enter fullscreen mode Exit fullscreen mode

Before go1.22.0:

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

In go1.22.0:

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

Thank you for reading!

Top comments (0)