Chapter 6. Pointers

Now that we’ve seen variables and functions, we’re going to take a quick look at pointer syntax. Then we’ll clarify the behavior of pointers in Go by comparing them to the behavior of classes in other languages. We’ll also learn how and when to use pointers, how memory is allocated in Go, and how using pointers and values properly makes Go programs faster and more efficient.

A Quick Pointer Primer

A pointer is simply a variable that holds the location in memory where a value is stored. If you’ve taken computer science courses, you might have seen a graphic to represent how variables are stored in memory. The representation of the following two variables would look something like Figure 6-1:

var x int32 = 10
var y bool = true
Variables in Memory
Figure 6-1. Storing two variables in memory

Every variable is stored in one or more contiguous memory locations, called addresses. Different types of variables can take up different amounts of memory. In this example, we have two variables, x, which is a 32-bit int, and y, which is a boolean. Storing a 32-bit int requires four bytes, so the value for x is stored in four bytes, starting at address 1 and ending at address 4. A boolean only requires a single byte (you only need a bit to represent true or false, but the smallest amount of memory that can be independently addressed is a byte), so the value for y is stored in one ...

Get Learning Go now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.