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!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️