Go Pointers
In Go programming, pointers allow us to work directly with memory addresses. We can use pointers to access and modify the values of variables in memory, for example.
Let’s start with memory addresses in Golang before moving on to pointers.
What Exactly Are Pointers?
A pointer is a variable whose value is the address of another variable, i.e. the memory location’s direct address. A pointer, like any other variable or constant, must be declared before it may be used to store any variable address. A pointer variable declaration takes the following general form:
var var_name *var-type
The pointer’s base type is type, which must be a valid C data type, and the pointer variable’s name is var-name. The asterisk * you used to declare a pointer is also the asterisk you use to multiply. The asterisk, on the other hand, is used to indicate a variable as a pointer in this statement. The valid pointer declarations are as follows:
var ip *int /* pointer to an integer */
var fp *float32 /* pointer to a float */
All pointer values, whether integer, float, or otherwise, have the same data type: a lengthy hexadecimal number that represents a memory address. The data type of the variable or constant to which the pointer points is the only variation between pointers of different data kinds.
Go Pointer Variables
In Go, we use the pointer variables to store the memory address. For example,
var num int = 5
// create the pointer variable
var ptr *int = &num
Here, we have created the pointer variable named ptr that stores the memory address of the num variable.
*int represents that the pointer variable is of int type (stores the memory address of int variable).
We can also create pointer variables of other types. For example,
// pointer variable of string type
var ptr1 *string
// pointer variable of double type
var ptr2 * float32
Let’s now see a working example of pointers.
Example: Pointer Variables
We can assign the memory address of a variable to a pointer variable. For example,
// Program to assign memory address to pointer
package main
import "fmt"
func main() {
var name = "John"
var ptr *string
// assign the memory address of name to the pointer
ptr = &name
fmt.Println("Value of pointer is", ptr)
fmt.Println("Address of the variable", &name)
}
Output
Value of pointer is 0xc00007c1c0
Address of the variable 0xc00007c1c0
In the above example, we have created a pointer variable named ptr of type string. Here, both the pointer variable and the address of the name variables are the same.
This is because the pointer ptr stores the memory address of the name variable.
ptr = &name