In Go, you use the &
operator to get the address of a variable and the *
operator to declare a pointer variable and to dereference a pointer.
To assign a value to a pointer, you first need to declare the pointer variable and then assign its address to it. You can then use the pointer to indirectly access and modify the value of the variable it points to.
main.go471 chars15 lines
In the above code, we declare an integer variable num
and a pointer variable ptr
of type *int
. We then assign the address of num
to ptr
using the &
operator.
We can then indirectly modify the value of num
by dereferencing the pointer using the *
operator and assigning a new value to it. The value of num
is then changed to 99.
Output:
main.go88 chars5 lines
gistlibby LogSnag