Home > database >  How to determine if the pointer passed as a function argument is being modified or a copy is being m
How to determine if the pointer passed as a function argument is being modified or a copy is being m

Time:01-04

package main

import (
    "fmt"
)

type Numbers struct {
    x int
    y int
}

func initial(number *Numbers) {
    number.x = 1
    number.y = 1
}

func final(number *Numbers) {
    number = &Numbers{2, 2}
}

func main() {
    p := Numbers{0, 0}
    fmt.Println(p) //Prints {0 0}

    initial(&p)
    fmt.Println(p) //Prints {1 1}

    final(&p)
    fmt.Println(p) //Expected to print {2, 2} but prints {1, 1}
}

Why does the initial function modify the pointer, while the final function modifies a copy of the pointer?

Both initial and final have their own memory address; initial manages to change p defined in main, while final can't.

Any explanation so as why this is the case would be greatly appreciated.

CodePudding user response:

To modify the data pointed to by a pointer, you must dereference the pointer. The dereference operator is *. However, Go will implicitly insert the dereference operation in some cases for ease of use. For example, number.x = 1 is translated to (*number).x = 1.

This implicit translation may be confusing, but you should see that if it that translation didn't happen, then the expression number.x = 1 would be meaningless, since number is a pointer type and pointers don't have fields.

So in summary, the initial function has implicit pointer dereference, while final does not.

If you changed final to explicitly and correctly dereference, *number = Numbers{2, 2}, then it will also change p.

CodePudding user response:

The initial function works on the passed pointer, which is pointing to the variable allocated in main. All changes are performed on the object allocated in main.

The final function receives the same pointer as an argument, however, it assigns the pointer to another Numbers instance. The object in main never changes.

There is no copying involved in either function.

  • Related