-3

I am trying to create a bunch of struct instance and append to a list after setting some values. This was reusing the variable. This was not working as it turns out golang was returning the same object. This is against what I expect. Is there any rationale for the behavior? What is the solution. Below is the code snippet from goplayground.

package main

import (
    "fmt"
)

type a struct {
I int
}

func main() {
b := new(a)

b.I = 10
fmt.Printf("Hello, playground %v p: %p", b, &b)

b = new(a)
b.I = 12
fmt.Printf(" Hello, playground %v p: %p", b, &b)

}

here is the output :

Hello, playground &{10} **p: 0x40c138** Hello, playground &{12} **p: 0x40c138**
joe
  • 1,136
  • 9
  • 17
  • 4
    You're not redeclaring `b`, you're assigning a new value. Why would the address of `b` change? – JimB Feb 17 '20 at 23:24
  • 1
    my expectation is new(a) is creating new object every time when I call new(a). If it is not, how do I ensure creating a new object? – joe Feb 17 '20 at 23:30
  • 3
    `new(a)` is creating a new object each time, which is why you see `10` and `12` in the output. Print the pointer value, not it's address https://play.golang.org/p/P0WY38PwKh_O – JimB Feb 17 '20 at 23:32

1 Answers1

2

On your example, you're printing the address of variable b, not the value

try this:

package main

import (
    "fmt"
)

type a struct {
    I int
}

func main() {
    b := &a{}

    b.I = 10
    fmt.Printf("Hello, playground %v p: %p", b, b)

    b = &a{}
    b.I = 12
    fmt.Printf(" Hello, playground %v p: %p", b, b)

}

Hello, playground &{10} p: 0x40e020 Hello, playground &{12} p: 0x40e02c

https://play.golang.org/p/58qP6ggV5K8

J-Jacques M
  • 978
  • 6
  • 16
  • make sense. Thanks! It solved my problem. My scenario was something like this - b := a{} aL := make([]*a, 1) for i :=0; i<10; i++ { b = a{} b.I = i aL= append(aL, &b) – joe Feb 18 '20 at 00:48
  • It was a bit misleading for me as golang didn't give any hint. – joe Feb 18 '20 at 00:48