GO Lang Pointers

Hi,
I have a question related to the pointers and struct in go. As you see in the screenshot below, the function calcArea expects a pointer and that is fine. Then the area is calculated without de-referencing the variable c which is a pointer, only when there is an assignment it is being de-referenced. How does that work. My understanding is pointer variable must always be de-referenced inside the function to make the changes to the original

The go compiler is fairly smart about handling pointers. While you dereference the pointer c as in (*c).area = area, the compiler can figure out in that context that you are using a pointer; c.area = area will also work for that reason. The fmt.Printf(“%+v”, c) statements are similar; the compiler is able to figure out how to “stringify” c, even if it is a pointer to a C struct.

1 Like