Hi, I’m attempting to learn Go and I’ve recently ran into some issues understanding pointers. I get that they reference to a specific bit of memory but I’m not sure how they are used and when they should be used. I’m also unsure what it means to deference a pointer with the ampersand. If someone could help me understand pointers that would be great.
A pointer represents the address of a variable in memory. The ampersand (&) creates a pointer to a variable, and the asterisk (*) dereferences the pointer for accessing the original value at that address. For example:
i := 1 // a variable
pi := &i // pi is now a pointer to i
i += 1 // increment i
fmt.Println(*pi) // *pi dereferences the pointer and thus is the same as i
You can use this for passing a pointer to a function, so that the function can modify the original value rather than just a copy.
Example:
package main
import "fmt"
func change(ptr *int, i int) {
*ptr += 1
i += 1
fmt.Println(" change(): *ptr is", *ptr)
fmt.Println(" change(): i is", i)
fmt.Println()
}
func main() {
i := 1
j := 1
ptr := &j
fmt.Println("main(): *ptr is", *ptr)
fmt.Println("main(): i is", i)
fmt.Println()
change(ptr, i)
fmt.Println("main(): *ptr is", *ptr)
fmt.Println("main(): i is", i)
}