Welcome to part 4 of the Go programming tutorial series. In the previous tutorial, we covered some function basics. Now, we're going to cover the last basic concept before creating a simple web app, which is pointers. Pointers allow you to reference from memory, which lets you do some interesting things. Let's do a basic run-through.
We'll start by defining a variable:
package main import "fmt" func main() { x := 15 }
If we want to point to x
, we can use the &
symbol, like so:
a := &x
This gives us the memory address, so if we do:
fmt.Println(a)
This should output: 0xc0420441c0
. We can read through pointers using *
before the variable. For example:
package main import "fmt" func main() { x := 15 a := &x // point to x fmt.Println(a) fmt.Println(*a) }
Giving us:
0xc042008250 15
Okay, so what's the point of this? Well, what if we re-defined the reading through of a
?
*a = 5
The a
variable was just a memory address, and the asterisk gets us to read through to the memory address, when we combine these two, we can actually modify the value at that memory address. Thus:
fmt.Println(x)
Gives us: 5
So, what might happen with:
*a = *a**a
Now what is the value of x? You shoudl be able to do it in your head. If not...
fmt.Println(x) fmt.Println(*a)
Now, how might you get the memory address using x
and a
?
fmt.Println(&x) fmt.Println(a)
Full code up to this point:
package main import "fmt" func main() { x := 15 a := &x // point to x (memory address) fmt.Println(a) // prints out the mem addr. fmt.Println(*a) // read a through the pointer, so this will print out a value (15 in this case) *a = 5 // sets the value pointed at to 5, which means x is modified (since x is stored at the mem addr) fmt.Println(x) // see the new value of x *a = *a**a // what is the value of x now? fmt.Println(x) // prints a value fmt.Println(*a) // prints a value fmt.Println(&x) // prints a memory address fmt.Println(a) // prints a memory address }