Help Understanding Pointers

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.

Thanks.

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)
}

(Playground link)

1 Like

You’re a life saver. I was hitting a point with Go that I had no idea what was going on. Pointers make way more sense when you put it that way.

Thank you very much!

Anytime! Glad i could help.

1 Like

Pointers can also be used to optimize Go’s pass by value semantics. An example of this is included in my post https://pocketgophers/why-use-pointers/.

1 Like

Hi, it might be easier to understand if you imagine that

& is getting the memory address of a variable
* is getting the value of a memory address (the pointer is pointing to)

And then you will not be surprised about:

a := 10
b := &a
c := &b
fmt.Println(a)   // 10
fmt.Println(b)   // 0xc420010f50
fmt.Println(c)   // 0xc42000e038
fmt.Println(*b)  // 10
fmt.Println(**c) // 10

Yes, it’s possible to point to a pointer’s address!

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.