Search code examples
linuxgogoland

redeclaring a struct instance to same variable name is returning old object in golang


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**

Solution

  • 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