The Analogy: The Pre-Printed Form
A well designed paper form arrives with every box already filled in with a sensible default. Quantity reads 0. The notes field is empty rather than absent. The checkbox for express delivery is printed unticked. Nothing on the page is undefined, and nobody has to remember to write "none" in the boxes they skipped, because the printer already decided what an untouched box means. You can hand that form to a clerk half completed and they can still process it, because a blank box has a known meaning rather than an unknown one.
Now imagine a form that arrives with whatever the previous user scribbled still faintly visible in each box. Quantity might read 47000 because that was the last order printed on that sheet. This is memory in C: a variable you declare but never assign contains whatever bytes happened to be sitting at that address, and the resulting bug appears only sometimes, only on some machines, and never while you are looking. Whole categories of security vulnerability come from reading a box the last user wrote in.
Some languages solve this with a third state: the box is neither zero nor a value, it is null, and touching it throws. That is safer than garbage but it moves the cost, because now every read has to ask whether the box was filled before it can be trusted, and the answer is only available at run time.
Go takes the pre-printed form approach and calls it the zero value. Declare an int and it is 0. Declare a string and it is the empty string, not null. Declare a bool and it is false. Declare a struct and every field inside it is zeroed recursively, all the way down. This is a guarantee from the language, not a habit you have to keep, and it is why so much Go code declares a variable and starts using it immediately: the useful state and the initial state are usually the same thing.
Syntax or Core Structure
Go has one concept, the variable, and several spellings of it. Which one you use is decided almost entirely by where you are standing.
package main
import "fmt"
// At package scope only var and const are legal. There is no := out here.
var release = "1.0"
const maxRetries = 3
func split(pair string) (string, string) {
for i := 0; i < len(pair); i++ {
if pair[i] == '=' {
return pair[:i], pair[i+1:]
}
}
return pair, ""
}
func main() {
var explicit int // declared, so it holds its zero value
var inferred = "go" // type inferred from the value, still a var
short := 3.5 // short form, only inside a function
var (
host string
port = 8080
tls bool
)
a, b := 1, 2
a, b = b, a // swap with no temporary variable
_, value := split("region=eu") // discard the first result
fmt.Printf("explicit %d, inferred %q, short %.1f\n", explicit, inferred, short)
fmt.Printf("host %q, port %d, tls %t\n", host, port, tls)
fmt.Printf("a %d, b %d\n", a, b)
fmt.Printf("value %q\n", value)
fmt.Printf("release %s, maxRetries %d\n", release, maxRetries)
}
Output:
explicit 0, inferred "go", short 3.5
host "", port 8080, tls false
a 2, b 1
value "eu"
release 1.0, maxRetries 3
The %q verb is worth adopting as a habit. It quotes the string, so an empty value prints as "" rather than as nothing at all, and a trailing space or a stray tab becomes visible instead of invisible. More debugging time is lost to a string that was not what you thought than to any arithmetic mistake.
Technical Depth: Zero Values, Scope and Layout
Every Type Has a Zero Value
| Type | Zero value | Safe to use immediately? |
|---|---|---|
int, int64, uint8, rune | 0 | Yes |
float64, complex128 | 0 | Yes |
bool | false | Yes |
string | "", length 0 | Yes, it is immutable and never null |
| Array | Every element zeroed | Yes |
| Struct | Every field zeroed, recursively | Yes, if its own zero value is meaningful |
Pointer, interface, func, chan | nil | No, calling or dereferencing panics |
| Slice | nil, length 0 | Partly: len, range and append work; indexing panics |
| Map | nil, length 0 | Reading works and returns the zero value; writing panics |
The last two rows are the ones that catch people, and they are asymmetric on purpose. append to a nil slice allocates and returns a working slice, so var items []string followed by items = append(items, "a") is idiomatic and correct. A nil map, by contrast, has nowhere to put anything, so assignment panics with assignment to entry in nil map and you must write make(map[string]int) first.
A type whose zero value is directly usable is described as having a useful zero value, and it is a design goal worth copying. sync.Mutex, bytes.Buffer and strings.Builder all work correctly when simply declared, with no constructor call.
var Against :=
| Situation | Use |
|---|---|
| Package scope | var or const, since := is illegal there |
| You want the zero value | var count int |
| You have a value already | count := 0 |
| The literal's default type is wrong | var ratio float64 = 3 or ratio := float64(3) |
| Declaring an interface variable to fill in later | var w io.Writer |
| Several related declarations | A var ( ... ) block |
The short form has one rule that surprises people: in a, err := f() followed later by b, err := g(), the second statement is legal even though err already exists, because at least one variable on the left is new. err is assigned, not redeclared. If every name on the left already exists, you must use =.
Shadowing Is Legal and Occasionally Expensive
A new block can declare a name that already exists in an outer block, and the inner one wins until the block ends.
config, err := load()
if err != nil {
return err
}
if config.Verbose {
config, err := load() // BUG: two new variables, thrown away here
_ = config
_ = err
}
The inner := created a second config and a second err that live only inside the if. The outer ones never change, the compiler does not object because both new variables are used, and the mistake survives review because the line looks like an assignment. This is what go vet with the shadow analyzer, and every serious linter, is looking for.
Constants Are Not Just Read-Only Variables
A Go constant is resolved at compile time and, if you do not give it a type, it stays untyped and adapts to where it is used.
const big = 1 << 40 // untyped, no overflow concern at declaration
const timeout = 30 // untyped, usable as an int or a time.Duration factor
var asFloat float64 = big // fine, converted at compile time
var asInt int32 = 1 << 40 // compile error: overflows int32
Untyped constants also have arbitrary precision during evaluation, so const third = 1.0 / 3.0 keeps far more digits than a float64 can hold and only rounds when it is assigned. Grouped constants can be numbered automatically with iota:
type State int
const (
Pending State = iota // 0
Active // 1
Closed // 2
)
What a Variable Actually Occupies
Go values have predictable sizes, and several types you think of as simple are small structs behind the scenes. The figures below are for a 64 bit platform.
| Type | Size | Contents |
|---|---|---|
bool, int8 | 1 byte | The value |
int32, float32, rune | 4 bytes | The value |
int, int64, float64, pointer | 8 bytes | The value or address |
string | 16 bytes | Pointer to bytes, length |
| Slice | 24 bytes | Pointer to array, length, capacity |
interface | 16 bytes | Pointer to type info, pointer to value |
Map, channel, func | 8 bytes | A pointer to the real structure |
This is why passing a string or a slice to a function is cheap regardless of how much data it refers to: you copy the small header, not the bytes. It is also why a slice header copy shares the same backing array, a fact that Module 3 spends a whole lesson on.
Real World Example: The Same Four Fields, Two Different Sizes
A telemetry service keeps a slice of readings in memory. The struct has four fields and nobody thought about their order, because in most languages the order of fields is a matter of taste. In Go, as in C, the compiler lays fields out in the order you wrote them and inserts padding so that each field starts at an address its type can be aligned to. Order is therefore a memory decision.
package main
import (
"fmt"
"unsafe"
)
// Written in the order the domain suggested.
type PaddedReading struct {
ok bool
value float64
flag bool
count int64
}
// The same four fields, widest first, single byte fields adjacent.
type PackedReading struct {
value float64
count int64
ok bool
flag bool
}
func main() {
var padded PaddedReading
var packed PackedReading
fmt.Printf("padded: %d bytes, alignment %d\n",
unsafe.Sizeof(padded), unsafe.Alignof(padded))
fmt.Printf("%-6s offset %2d\n", "ok", unsafe.Offsetof(padded.ok))
fmt.Printf("%-6s offset %2d\n", "value", unsafe.Offsetof(padded.value))
fmt.Printf("%-6s offset %2d\n", "flag", unsafe.Offsetof(padded.flag))
fmt.Printf("%-6s offset %2d\n", "count", unsafe.Offsetof(padded.count))
fmt.Printf("packed: %d bytes, alignment %d\n",
unsafe.Sizeof(packed), unsafe.Alignof(packed))
fmt.Printf("%-6s offset %2d\n", "value", unsafe.Offsetof(packed.value))
fmt.Printf("%-6s offset %2d\n", "count", unsafe.Offsetof(packed.count))
fmt.Printf("%-6s offset %2d\n", "ok", unsafe.Offsetof(packed.ok))
fmt.Printf("%-6s offset %2d\n", "flag", unsafe.Offsetof(packed.flag))
saved := unsafe.Sizeof(padded) - unsafe.Sizeof(packed)
fmt.Printf("saved per record: %d bytes\n", saved)
fmt.Printf("saved per million records: %d bytes\n", saved*1000000)
}
Output:
padded: 32 bytes, alignment 8
ok offset 0
value offset 8
flag offset 16
count offset 24
packed: 24 bytes, alignment 8
value offset 0
count offset 8
ok offset 16
flag offset 17
saved per record: 8 bytes
saved per million records: 8000000 bytes
Read the offsets and the padding becomes visible without any tooling. In PaddedReading, ok occupies byte 0 and value starts at byte 8, so bytes 1 to 7 are dead space that exists only because a float64 must begin at an address divisible by 8. The same thing happens again between flag at byte 16 and count at byte 24. Two single byte fields cost eight bytes each. In PackedReading the two bool fields sit next to each other at bytes 16 and 17, share one gap at the end of the struct, and the whole record fits in 24 bytes.
The rule that produces this is simple enough to apply by eye: declare fields from widest alignment to narrowest, and keep bool, int8 and other single byte fields together. You do not need to compute anything, and you do not need to reorder every struct in your program. It matters when a struct is allocated in bulk, which means slices of records, cache entries, graph nodes and anything you keep a million of. For a config struct that exists once, field order should follow whatever reads best.
Notice also what unsafe did here, which is nothing dangerous at all. unsafe.Sizeof, unsafe.Alignof and unsafe.Offsetof are resolved by the compiler into constants, they never read memory, and using them does not make a program unsafe in any meaningful sense. The genuinely sharp tool in that package is unsafe.Pointer, which Module 9 covers. If you would rather not import unsafe at all, the fieldalignment analyzer from golang.org/x/tools reports over-padded structs across a whole package and can rewrite them for you.
One warning about drawing conclusions from these numbers: they describe a 64 bit platform. On a 32 bit target a pointer is four bytes and int is four bytes, so both totals change, and code that hard codes a size or an offset breaks. That is exactly why unsafe.Sizeof exists as a compile time expression rather than a number you write down. Measure the layout, never memorize it.
Common Mistakes
- Writing to a nil map.
var counts map[string]intthencounts["a"]++panics withassignment to entry in nil map. Reading from a nil map is fine and returns the zero value, which makes the asymmetry easy to miss. Usemake(map[string]int)or a literal.
- Assuming a nil slice is broken. It is not.
len,cap,rangeandappendall work on it, sovar items []stringis the correct way to start a list you are about to build. Only indexing into it panics.
- Shadowing
errinside aniforforblock. The inner:=makes a new variable, the outer one keeps its old value, and the code compiles. If a variable mysteriously fails to change, look for a:=where you meant=.
- Reaching for
:=at package scope. It is a syntax error outside a function. Package level state needsvaror, better, no package level state at all.
- Declaring a variable before you need it, C style. Go's short form means you can declare at the point of first use, inside the narrowest block that needs it. A variable declared thirty lines early is a variable somebody has to keep in their head for thirty lines.
- Using
ALL_CAPSfor constants. Go usesMaxRetriesandmaxRetries; the case of the first letter already carries meaning, and screaming case carries none.
- Expecting an untyped constant to overflow at declaration.
const big = 1 << 62is fine on its own and only fails when assigned to a type too small to hold it. The error points at the assignment, not the constant.
- Forgetting that a struct copy is a full copy. Assigning a struct copies every field, including a
sync.Mutexif there is one, which silently gives you a second unrelated lock.go vet'scopylockscheck exists for this.
- Optimizing field order everywhere. Padding is worth removing in the structs you keep millions of. Doing it to a struct that exists once trades readability for nothing.
Best Practices
- Design types whose zero value is already usable, the way
bytes.Bufferandsync.Mutexdo, so callers need no constructor. - Declare with
varwhen you want the zero value and with:=when you already have the value; do not writex := 0wherevar x intsays it better. - Declare variables in the smallest scope that needs them, at the point of first use.
- Use
%qwhen printing strings during debugging so empty values and stray whitespace become visible. - Initialize maps with
makeor a literal at the moment you declare them, and let slices start asnil. - Group related constants in a
constblock, and useiotawith a named type when they form an enumeration. - Prefer passing a pointer to a large struct, and remember that strings, slices and maps are already cheap to copy because they are headers.
- Order struct fields widest first when the type will exist in bulk, and check the result with
unsafe.Sizeofrather than guessing.
Practice Exercises
- Zero Value Survey: Write a program that declares one variable of each of these types without assigning to it, then prints all of them with
%#v:int,float64,bool,string,[3]int, a two field struct, a slice, a map, a pointer and anerror. Note which three print asniland explain which operations are still legal on each.
- Provoke Both Failures: Write a program that appends to a nil slice successfully and then, in the next statement, writes to a nil map and panics. Record the exact panic message, then fix the map with one word and explain why the slice never needed fixing.
- Catch a Shadow: Write a function that loads a config, then re-declares both
configanderrinside anifblock with:=. Print the outerconfigafterwards and show that it did not change. Then fix it with a single character, and note which linter flags the original.
- Shrink a Record: Define a struct with a
bool, anint64, anint32, astringand anotherboolin that order. Printunsafe.Sizeofand every field'sunsafe.Offsetof. Reorder the fields to make it as small as possible, print the new size, and calculate how much memory a slice of ten million such records would save.