Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reference pointers to the same struct object from outside the scope in which they were defined

In the below code, two pointer variables, r1 and r2 (of type *Rect), reference the same struct object (of type Rect):

type Rect struct {
    width int
}

func main() {
    r1 := new(Rect)
    r2 := new(Rect)
    r1 = r2

    fmt.Printf("%p, %p", r1, r2) // prints the addresses of the Rects being pointed to by each variable
}

0xc00001c038, 0xc00001c038 (GOOD OUTPUT)

How would you reference r1 and r2 to the same struct object from outside of the function in which they were defined? In other words, how would you create a function to replace r1 = r2? My attempt at dereferencing and then assigning the variables from within an external function did not succeed at referencing r1 to r2‘s referenced struct object:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

func assign(r1, r2 *Rect) {
    *r1 = *r2
}

func main() {
    r1 := new(Rect)
    r2 := new(Rect)
    assign(r1, r2)

    fmt.Printf("%p, %p", r1, r2) // prints the addresses of the Rects being pointed to by each variable
}

0xc00001c030, 0xc00001c038 (BAD OUTPUT)

PLAYGROUND: https://go.dev/play/p/ld0C5Bkmxo3

>Solution :

If you need to change where a pointer points to within a function, you have to pass the address of it:

func assign(r1, r2 **Rect) {
    *r1 = *r2
}

func main() {
    r1 := new(Rect)
    r2 := new(Rect)
    assign(&r1, &r2)

    fmt.Printf("%p, %p", r1, r2) // prints the addresses of the Rects being pointed to by each variable
}

PLAYGROUND: https://go.dev/play/p/5fAakjB50JJ

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading