Skip to Content
Learning Go
book

Learning Go

by Jon Bodner
March 2021
Beginner
375 pages
8h 59m
English
O'Reilly Media, Inc.
Content preview from Learning Go

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 byte at address ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Go, 2nd Edition

Learning Go, 2nd Edition

Jon Bodner

Publisher Resources

ISBN: 9781492077206Errata PageSupplemental Content