By placing the dereference operator (an asterisk) before a pointer, you gain access to the value stored in the pointer’s referenced memory location. Moreover, you can modify the value by using the dereference operator in an assignment.
Basic Syntax
To read and modify the value of the variable pointed to by a pointer, use the following syntax:Example 1: Simple Dereferencing
Consider this example where we have a variablex holding a numeric value and a pointer ptr that stores the address of x:
ptr stores an address (e.g., 0x0301). When we dereference ptr and assign a new value, x is updated accordingly:
Example 2: Practical Pointer Dereferencing in Go
This Go program demonstrates a practical application of pointer dereferencing using a string variable. Initially, the string variables is set to “hello”. We then create a pointer ps (using the shorthand operator) to store the address of s. By dereferencing ps, we update the value of s from “hello” to “world”. The program prints the type and the updated value of s.
Regular practice of these examples in your Go development environment will help reinforce your understanding of pointer dereferencing.