Go Pointers

h‮:sptt‬//www.theitroad.com

In Go, a pointer is a variable that stores the memory address of another variable. Pointers are useful when you want to modify the value of a variable passed to a function or when you want to allocate memory dynamically.

To declare a pointer in Go, you use the * symbol followed by the type of the variable being pointed to. For example, the following code declares a pointer to an integer:

var p *int

This declares a pointer variable named p that can point to an integer value. Note that at this point, p does not point to anything yet; it is just a pointer variable with a value of nil.

To get the address of a variable in Go, you use the & operator followed by the variable name. For example, the following code gets the address of an integer variable x:

var x int = 42
var p *int = &x

This declares an integer variable x with a value of 42, and then declares a pointer variable p that points to x.

To get the value of a variable through a pointer in Go, you use the * operator followed by the pointer variable name. For example, the following code gets the value of x through the pointer p:

fmt.Println(*p) // prints "42"

This code dereferences the pointer p and returns the value of the integer variable it points to.

To modify the value of a variable through a pointer in Go, you can use the * operator to set the value of the variable. For example, the following code modifies the value of x through the pointer p:

*p = 99
fmt.Println(x) // prints "99"

This code sets the value of the integer variable that p points to to 99, which also changes the value of x.