Pointers in Go: A Pragmatic Guide to Memory Manipulation
Before we embark on our journey through the world of pointers in Go, we must fist grasp the significance of the & operator.
func main() {
var i int = 10
// & is the address-of operator in Go, which returns the memory address of the variable
// pronounced as “ampersand” in English.
fmt.Println("the address of i is", &i)
}
When a variable is used to store the memory address of another variable, it is indeed referred to as a pointer.
func main() {
var i int = 10
// & is the address-of operator in Go, which returns the memory address of the variable
fmt.Println("the address of i is", &i)
// when a variable is used to store the memory address of another variable, it is indeed referred to as a pointer.
var ptr = &i // ptr is a pointer variable
// var ptr *int = &i
}
When placed before a pointer variable, the * operator is used to dereference the pointer, meaning it accesses the value stored at the memory address that the pointer is referencing.
func main() {
var i int = 10
// & is the address-of operator in Go, which returns the memory address of the variable
fmt.Println("the address of i is", &i)
// when a variable is used to store the memory address of another variable, it is indeed referred to as a pointer.
var ptr = &i // ptr is a pointer variable
// So we can guess the value of ptr equals the address of i
fmt.Println(ptr)
// Dereferencing the pointer to get the value it points to
fmt.Printf("value pointed to by ptr is %d\n", *ptr) // This will print the value of i, which is 10
}
We've covered the basics of pointers in Go, including how to obtain the address of a variable, how to declare a pointer, and how to dereference a pointer to access the value it points to. Understanding these concepts is crucial for effective memory manipulation in Go.

浙公网安备 33010602011771号