Skip to content

Instantly share code, notes, and snippets.

@strazzere
Created May 24, 2023 16:53
Show Gist options
  • Save strazzere/f3a6b1cdbc07f55939161ff4deab39c7 to your computer and use it in GitHub Desktop.
Save strazzere/f3a6b1cdbc07f55939161ff4deab39c7 to your computer and use it in GitHub Desktop.
Spot the bug, point to array appending in golang
package main
import (
"fmt"
)
func test() []*int {
ints := []int{1, 2, 3, 4, 5}
var newInts []*int
for index, integer := range ints {
fmt.Printf("%v : %v\n", integer, &integer) // Pass the address of the beginning address
fmt.Printf("%v : %v\n", ints[index], &ints[index]) // Pass the correct address of element
newInts = append(newInts, &ints[index])
}
return newInts
}
func main() {
var allInts []*int
for i := 0; i < 1; i++ {
ints := test()
allInts = append(allInts, ints...)
}
fmt.Printf("%v\n", allInts)
for _, integer := range allInts {
fmt.Printf("%v\n", *integer)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment