Isn't this pointer indicator confusing?

Hi all,

I’m learning pointer and noticed that when defining pointer we use &a (assume a is a variable) but use *a when pointer is used in func (either as receiver or as a returned type). so, to me new to golang, I feel this is a bit confusion. what do you think?

thanks
James

The “&” operator returns the address of a variable and typically you assign to a variable of pointer type.
“*” defines a variable as a pointer (For example *int could be read it as pointer to int)

thanks @Yamil_Bracho for quick response but that’s what I’m confused. so, let’s say a := 1, then define a pointer as p := &a, notice that pointer is just a variable p without any prefix (no *). then when we do dereference, we use *p to get the value of a.

if this is true, then adding prefix * to a pointer is to dereference which calls the variable value stored in the memory address of p.

so my question remains that when we do func (ob *somevariable) () {} isn’t that confusing by using * for pointer?

&a gives the address of variable to the pointer, not creates a pointer.
For example

package main

import (
	"fmt"
)

func main() {
	a := 1
	p := &a

	var q *int = &a

	fmt.Printf("a=%d, p=%v, q=%v", a, p, q)
}
1 Like

here is the result I get:

a=1, p=0xc000016098, q=0xc000016098

so p and q are same. so you think p is not a pointer but q is?

1 Like

Both are pointers.
So doing p:= &a it is the same as you can write var p *int = &a

1 Like

Got it thanks!

1 Like

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