*
)*
attached to a type (e.g. *string
) indicates a pointer
to the type.
*
attached to a variable in an assignment (e.g. *v = ...
) indicates an indirect assignment
value
pointed at by the variablePointer
does not change to point to a new location in memory with a different value
, but the underlying value
is changed*
attached to a variable or expression (e.g. *v
) indicates a pointer dereference
value
the variable is pointing at&
attached to a variable or expression (e.g. &v
) indicates a reference
(memory address)
pointer
to the value
of the variable or to the field// declare a variable of type "int" with the default value "0" var y int // declare a variable of type "int pointer" // x may only hold addresses to variables of type "int" var x *int
y
may not simply be assigned to x
, like x = y
, because that would raise an error, since x
is of type int pointer
, but y
is of type int
.
// assign address of y "0xc42008c0a0" as value of x x = &y // print the value of x "0xc42008c0a0" which is also the address of y fmt.Println(x)
x
and y
still have different addresses, even though x
has a value
identical to the address of y
// print the address of x, something like "0xc420030028" fmt.Println(&x)
Dereferencing
a pointer
gives us access to the value
the pointer
points to
// x is of type "int pointer" and holds an address to a variable of type "int" (y)that holds the value "0", something like x -> y -> 0; // print the value of y "0" via x (dereference) fmt.Println(*x) // change the value of y via x *x = 1; // same as y = 1 // print value of y, which is 1 fmt.Println(y); // same as fmt.Println(*x)
Cannot de-reference to null