Chapter 6. Pointers
Now that you’ve seen variables and functions, it’s time to learn about pointer syntax. Then I’ll clarify the behavior of pointers in Go by comparing them to the behavior of classes in other languages. You’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 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 the way 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
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, you 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 requires only a single byte (you need only 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 byte at address 5, with ...
Get Learning Go, 2nd Edition 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.