In Go, pointers are used to store memory addresses of values instead of the actual values themselves. Here's how you can create and use pointers in Go:
To create a pointer, you need to use the asterisk (*) symbol followed by the type of the variable you want to point to. For example, to create a pointer to an integer value, you would use var ptr *int
.
To assign a value to a pointer, you can use the &
operator followed by the variable you want to take the address of. For example, if you have an integer variable num
, you can assign its address to the pointer ptr
using ptr = &num
.
To access the value pointed to by a pointer, you can use the asterisk (*) operator again. For example, if you have a pointer ptr
, you can access the value it points to using *ptr
.
Here's an example that demonstrates how to create and use pointers in Go:
package main
import "fmt"
func main() {
var num int = 42
var ptr *int
ptr = &num
fmt.Println("Value:", num)
fmt.Println("Address:", ptr)
fmt.Println("Dereferenced value:", *ptr)
*ptr = 24
fmt.Println("New value:", num)
}
In this example, num
is an integer variable, ptr
is a pointer to an integer, and we assign the memory address of num
to ptr
. We then print the value, address, and the dereferenced value of ptr
, which should be the same as num
. Finally, we change the value of num
indirectly by modifying the value through the pointer, which affects the original variable num
.
The output of this program would be:
Value: 42
Address: 0x40e020
Dereferenced value: 42
New value: 24