Pointer of struct VS variable

type Point struct {
	x_value int
	y_value int

func changePointX(pt *Point, new_x_value int) {
	pt.x_value = new_x_value                                        <-------------------------------------

func updateName(n *string) {
	*n = "wedge"                                                        <-------------------------------------

func main() {
	point1 := &Point{1, 2}
	fmt.Printf("point 1: %v\n", point1)
	changePointX(point1, 100)
	fmt.Printf("point 1: %v\n", point1)

	name := "tifa"
	m := &name

hello ppl ,
i would like to understand why am i using

*n = "wedge" 

when i want to update a value of string , and when i want to update a value of a struct i am using :

pt.x_value = new_x_value

when pt.x is without astrix (*) in the beginning - i think it is also should be like this :
*pt.x_value = new_x_value <— but this is not working and the code up is working.

what am i missing ?

thanks a lot in advance.
Lipnitsky Edgar

The asterisk would dereference pt.x_value, which is an int, not a pointer.

The dot/field accessor does automatic dereferencing when necessary.

This doesn’t work because it needs parentheses to override the operator priorities (*pt).x_value, but @NobbZ explains the correct idiom.

@NobbZ - so the key to your answer is when i am using struct.field the “.” (dot) will deference pointer as needed , but what comes to mind is when go decides that it is needed or not and based on what ?

@mje - can u plz elaborate why the round brackets will make this work ?

If the LHS of the dot is a pointer, it will get dereferenced for the field access, if it’s not it won’t get derefed.

As a rule of thumb, whenever you’d use a -> in C, go will deref for you.

Because then you force the asterisk to be bound to the pointer and will therefore dereference before doing the field access.

1 Like

@NobbZ / @mje - thank you very much , appropriate your help !!

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.