We define a variable with a value and a name. The variable name will be converted to a memory address and the value gets stored in that address. In case of a pointer variable, an actual memory address of another variable is stored as a value.
The two unary pointer operators.
-
&
is used to get the memory address of a variable -
*
is used to get value at the address stored by a pointer variable.
Example:
func main() { x := 7 y := &x // creating a pointer variable p := fmt.Println pf := fmt.Printf pf("type of x (non pointer variable) = %T\n", x) p("value of x (stores actual data) =", x) p("address of x (memory address where x is located) =", &x) // invalid operation: cannot indirect x (variable of type int) // p("value dereferenced by x =", *x) p() pf("type of y (pointer variable) = %T\n", y) p("value of y (stores memory address of x) =", y) p("address of y (memory address where y is located) =", &y) p("value at the address stored by y (dereferencing the pointer) =", *y) }
Output
type of x (non pointer variable) = int value of x (stores actual data) = 7 address of x (memory address where x is located) = 0xc00001a0e8 type of y (pointer variable) = *int value of y (stores memory address of x) = 0xc00001a0e8 address of y (memory address where y is located) = 0xc000012028 value at the address stored by y (dereferencing the pointer) = 7
Resources:
Top comments (3)
Thanks for sharing it!😀
Is there any difference between go pointers and C pointers?