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

tech · Feb 17, 2024 · ~2 min
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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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)
	}
}

Before go1.22.0:

1
2
3
$ go run main.go 
[1 2 3]
3 3 3

In go1.22.0:

1
2
3
$ go run main.go
[1 2 3]
1 2 3 

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.

Drop Your Comment Below