go

Will shorthand declaration of variable, involving already defined one, allocate new memory?


I have a function that returns to values user and err . When I call it in scope I already have variable user, but don’t have variable err , so compiler/linter tells me to use := operator syntax (I know I can declare err somewhere before this call with var declaration), making it look like this:

user := User{"Name"}
...
user, err := functionThatReturnsTwoValues()
if err != nil {
...

Question: In this specific case, in the line user, err := functionThatReturnsTwoValues , will user variable be redeclared?

P.S. I also understand that from actual results, it doesn't matter for me, as in the end, I will have variable with correct data after function call in any case. Also the fact, that variable will be defined in the stack in our case, means there will be no garbage collection involved to clean it up, even if there were 2 User structs initialized.


Solution

  • I think user variable is not re-declared, but of course its value is overridden. I've tested via checking the variable's pointer addresses as below. As you may see the pointers which are used for capturing variable addresses stays same.

    https://play.golang.org/p/bj3QwSgCCiG

    Snipped:

    func main() {
        user := User{"Name"}
        up1 := &user
    
        user, err := functionThatReturnsTwoValues()
        up2 := &user
    
        if err == nil {
            fmt.Printf("User: %v \n", user)
            fmt.Printf("Pointer check :  up1 ?=  up2 --> %t [up1=%p, up2=%p]\n", up1 == up2, up1, up2)
            fmt.Printf("Value check   : *up1 ?= *up2 --> %t \n", *up1 == *up2)
        }
    }
    

    The output is:

    User: {Name2}  
    Pointer check :  up1 ?=  up2 --> true [up1=0x40c138, up2=0x40c138]
    Value check   : *up1 ?= *up2 --> true