Appendix B. Variables and pointers

 

Truly grasping Go's mechanics requires an understanding of pointers.

Many languages use pointers implicitly. Take Java, for instance: Every object is essentially a pointer, allowing Java programmers to modify objects across methods. Unlike Java or others, Go leaves us the decision of using a pointer for precise control over memory.

Once we go over variables, we can move on to pointers and pass-by-value semantics.

B.1 Variables

In Go, every variable should be declared. Variables have a fixed type (e.g., int), and their types can't change once declared. We can declare variables with or without an initial value.

TIP

Go is statically typed; we cannot change a variable type after declaring.

If we skip the initial value, Go sets the variable to its type's zero value (e.g., 0 for numbers). This approach reduces the risk of memory corruption or security bugs common in C, where uninitialized variables can end up with garbage values from random parts of memory.

TIP

Variables declared without an initial value get a zero value. For numbers, it's 0; for strings, it's an empty string—""; for booleans, it's false; for pointer types, it's nil.

We can declare a variable without an initial value using the var keyword:

var title string  #A

Declaring a variable without an initial value is idiomatic if we want to assign values later in the code. It's also the only syntax we can use to declare package-level variables.

B.2 Pointers

B.2.1 What is a pointer?

B.2.2 Nil pointers and type safety

B.2.3 Address operators

B.2.4 Pass-by-value mechanics

B.2.5 Stack and heap memory

B.3 Exercises