Values, Variables, Constants, iota Enums & Zero Values
"Constant expressions are always evaluated exactly; intermediate values and the constants themselves may require precision significantly larger than supported by any predeclared type in the language." — The Go Programming Language Specification, section "Constant expressions"
Summary: Every Go value has a static type and a zero value; constants are exact, untyped numbers that only become a typed value when they meet a variable, which is why iota enums, nil and numeric conversions behave the way they do. Focus: Basic types and sizes, string immutability, untyped and typed constants, var versus := versus const, shadowing, zero values, nil and typed nil, conversions versus type assertions, iota enums and bit flags, stringer, named types versus aliases, scope, numeric traps, unsafe.Sizeof, go vet and staticcheck. Learning goal: Predict the type and value of every expression, design an enum whose zero value is safe and that survives JSON and SQL, avoid silent truncation and shadowing bugs, and read the compiler and vet messages that point at them.
This page is the complete reference for how Go holds data in variables and constants. It owns types and sizes, constants, iota, zero values, conversions, scope and the enum idioms. It does not re-teach its neighbours: pointers and escape analysis live in Pointers & Memory Model Basics, slices and maps in Arrays, Slices & Maps, interfaces and type switches in Interfaces, Type Assertions, Type Switches & any, runes and formatting in Strings, Runes, fmt Verbs, text/template & regexp, JSON in JSON, XML, Struct Tags, Encoder/Decoder, Base64, and for/switch in Control Flow.
Page map
| If you are looking for | Go to |
|---|---|
| Tables you can memorise in one minute | Everything in one minute |
| Why Go has untyped constants and zero values | Why it exists |
| Spec, Effective Go, the constants blog post | Where it comes from |
int versus int64, uint, float64, complex128, byte, rune, bool | Basic types and sizes |
Why s[0] = 'J' does not compile | Strings and immutability |
1 << 100, 0.1 + 0.2, default types | Untyped constants |
const, typed constant, constant expression | Typed constants and overflow |
var, :=, package-level declarations | var versus := |
The name that never changes | Shadowing |
0, "", nil, usable sync.Mutex and bytes.Buffer | Zero values |
err != nil is true but the function succeeded | nil and typed nil |
float64(i) versus x.(string) | Conversions versus type assertions |
uint(-1), int8(200), math.MaxInt64 + 1 | Numeric conversion traps |
iota, skip zero, Weekday, ByteSize | iota |
Status enums with String() and stringer | Enums |
1 << iota, &^, permissions | Bit flags |
JSON and database/sql for enums | Enum marshalling |
type A B versus type A = B | Named types and aliases |
Blocks, if x := ..., loop variables | Scope and blocks |
a, b = b, a, evaluation order | Multiple assignment |
math.MaxInt64, unsafe.Sizeof, padding | math constants and unsafe.Sizeof |
go vet, shadow, staticcheck findings | Vet and staticcheck |
| Exact messages | Mechanics |
| Fixes for classic bugs | Solving the classic problems |
| Before/after code | Go |
| Which construct for which job | Choosing |
| Monolith to distributed system | In architecture |
| Runnable experiments | Lab |
| Wrong beliefs, cheat sheet, terms | Misconceptions, Cheat sheet, Glossary |
Everything in one minute
The ideas. Each row is unpacked in the concept catalogue.
| Idea | In plain words | Tiny example | What goes wrong |
|---|---|---|---|
| Static type | Every variable has one type fixed at compile time | var n int64 | Mixing int and int64 is a compile error |
| Zero value | A declared variable is never uninitialised | var s string is "" | A zero value that looks valid but means "not set" |
| Untyped constant | A literal or const with no type until used | const Big = 1 << 100 | Assigning it to a too-small type is rejected |
| Default type | The type a constant gets in := | x := 3.14 is float64 | x := 5 / 2 is 2, not 2.5 |
iota | A counter inside one const block | A = iota is 0, B is 1 | A reordered block silently renumbers stored values |
| Shadowing | := in an inner block declares a new variable | if x, err := f(); ... | The outer variable never changes |
| Typed nil | An interface holding a nil pointer is not nil | var e *MyErr; return e | err != nil is true on success |
| Conversion | Explicit change of type: T(x) | float64(i) | Truncation and wrap-around without an error |
The numeric types.
| Type | Size | Range or meaning | Use it for |
|---|---|---|---|
int, uint | 32 or 64 bits (platform) | math.MaxInt64 on 64-bit | Indexes, lengths, counts |
int8 int16 int32 int64 | 1, 2, 4, 8 bytes | Two's complement | Wire formats, database columns, exact width |
uint8 (byte) uint16 uint32 uint64 | 1, 2, 4, 8 bytes | 0 up to 2^n - 1 | Bytes, bit sets, hashes |
uintptr | Pointer-sized unsigned integer | An address as a number, not a reference | unsafe code only |
float32, float64 | 4, 8 bytes | IEEE 754 binary floating point | float64 for almost everything |
complex64, complex128 | 8, 16 bytes | Real plus imaginary part | Signal processing; rare in services |
rune (int32) | 4 bytes | One Unicode code point | Iterating text by character |
bool | 1 byte | true, false | Flags and conditions |
string | 16 bytes header | Immutable bytes, usually UTF-8 | Text |
The errors you will meet.
| Message | Meaning | First move |
|---|---|---|
cannot use 200 (untyped int constant) as int8 value in variable declaration (overflows) | A constant does not fit the type | Pick a wider type or fix the value |
invalid operation: x + y (mismatched types int and float64) | No implicit numeric conversion | Convert one operand explicitly |
declared and not used: err | A local is never read | Use it or assign to _ |
result parameter err not in scope at return | A bare return after shadowing a named result | Use = not :=, or return values explicitly |
assignment to entry in nil map | Writing into a nil map panics | make the map first |
interface conversion: interface {} is string, not int | A single-value type assertion failed | Use the v, ok := x.(T) form |
conversion from int to string yields a string of one rune, not a string of digits | go vet stringintconv | strconv.Itoa or string(rune(i)) |
Why it exists
Go wants programs that are easy to read and fast to compile, with no hidden conversions. That produces two design choices that surprise people from PHP or JavaScript: values have exact static types with no implicit numeric conversions, and constants are a separate, more flexible world that is resolved before the program runs.
| Choice | Benefit | Cost |
|---|---|---|
| No implicit numeric conversion | int and int64 never mix silently, so wrap-around is visible in the source | You write float64(n) and int64(n) often |
| Zero value for every type | No uninitialised memory; many types need no constructor | The zero value can look valid when it means "unset" |
| Untyped exact constants | time.Second * 2 and 1 << 40 just work | A constant behaves differently from a variable of the same value |
iota instead of an enum keyword | One small mechanism covers sequences, bit flags and units | No built-in validity check, no automatic String() |
Lexical block scope with := | Short code, no declaration ceremony | Accidental shadowing |
Everyday picture. Think of constants as exact numbers written on paper, in a ruler-less world where 1 followed by 100 zeros is fine. A variable is a labelled box of a fixed size. You may write the paper number into the box only if it fits, and the compiler checks that while it compiles. After that, the box is a real machine word and arithmetic on it wraps around like a car odometer.
Three common misunderstandings, up front
- "A
constis just a variable that cannot change." No: an untyped constant has no type and unlimited precision until it is used, soconst x = 5can be anint, afloat64or atime.Durationdepending on the use. - "Go has enums." It does not; it has typed constants and
iota. Nothing stopsStatus(42)from existing. - "
nilis one value." There are nil pointers, slices, maps, channels, functions and interfaces, and an interface holding a nil pointer is itself not nil.
Where it comes from
The rules on this page are written down in the language specification: the sections on constants, constant expressions, iota, conversions, "The zero value", alias declarations and scope are the authority. Effective Go explains the idiom "make the zero value useful" and gives the ByteSize example for iota. Rob Pike's blog post Constants explains why untyped constants exist: numeric constants should "work as you expect: like numbers". The Go FAQ answers "Why is my nil error value not equal to nil?". Alias declarations arrived in Go 1.9 and generic type aliases in Go 1.24; per-iteration loop variables arrived in Go 1.22; the omitzero JSON option arrived in Go 1.24. All sources were read from go.dev on 2026-11-26.
| Feature | Since | Source |
|---|---|---|
Alias declarations type A = B | Go 1.9 | Spec, "Alias declarations" |
go vet without the -shadow flag; shadow as a separate tool | Go 1.12 | Go 1.12 release notes |
for loop variable per iteration, for i := range 10 | Go 1.22 | Go 1.22 release notes |
| Generic type aliases | Go 1.24 | Go 1.24 release notes |
omitzero in encoding/json struct tags | Go 1.24 | Go 1.24 release notes |
The concept catalogue
Basic types and sizes Must-know
In plain words: Go has a small set of built-in number, boolean and string types, each with a fixed size except int, uint and uintptr, which follow the machine word.
Common misunderstanding: "int is 32 bits." On 64-bit platforms it is 64 bits. On a 32-bit build it is 32. Code that stores an int in a file or on the wire changes meaning between platforms, so use int64 or int32 there.
Definition: int, uint and uintptr have implementation-specific sizes; the spec lists the other integer types with exact sizes, and byte is an alias for uint8, rune an alias for int32.
1 var x int8 = 127
2 x++ // wraps to -128 at run time, no panic, no error
3 var u uint8 = 0
4 u-- // wraps to 255
5 i := 9223372036854775807 // MaxInt64 on 64-bit
6 i++ // -9223372036854775808Real scenario: a user ID that fits in int on your laptop is stored in a PostgreSQL integer column (32 bits) and silently wraps in a conversion; a counter reaches 2^31 on a 32-bit ARM build; an int timestamp in nanoseconds overflows where int64 would not.
| Type | PostgreSQL column | MySQL column | Wire (Protocol Buffers) |
|---|---|---|---|
int32 | integer | INT | int32 |
int64 | bigint | BIGINT | int64 |
uint8 | smallint (no unsigned type) | TINYINT UNSIGNED | uint32 (no 8-bit type) |
float64 | double precision | DOUBLE | double |
bool | boolean | TINYINT(1) | bool |
How to use it: use int for lengths, indexes and loop counters (the standard library does), a fixed-width type when the size is part of a contract, and float64 for fractions. Never use floats for money: store integer minor units (cents) or a decimal type, see Schema Design.
// Package sizes shows how big the basic types are and how field order
// changes the size of a struct.
package sizes
import (
"math"
"unsafe"
)
// Padded lists small and large fields alternately; the compiler inserts
// padding so each field is aligned to its own size.
type Padded struct {
A bool
B int64
C bool
D int32
E bool
}
// Packed holds the same fields, largest first, so padding shrinks.
type Packed struct {
B int64
D int32
A bool
C bool
E bool
}
// Row is one line of the size table.
type Row struct {
Name string
Size uintptr
}
// Table returns the size in bytes of the common types on this platform.
func Table() []Row {
var (
b bool
i8 int8
i int
i6 int64
u uint
up uintptr
f float64
c complex128
s string
sl []int
m map[string]int
ch chan int
fn func()
in any
r rune
by byte
)
return []Row{
{"bool", unsafe.Sizeof(b)},
{"int8", unsafe.Sizeof(i8)},
{"byte", unsafe.Sizeof(by)},
{"rune", unsafe.Sizeof(r)},
{"int", unsafe.Sizeof(i)},
{"int64", unsafe.Sizeof(i6)},
{"uint", unsafe.Sizeof(u)},
{"uintptr", unsafe.Sizeof(up)},
{"float64", unsafe.Sizeof(f)},
{"complex128", unsafe.Sizeof(c)},
{"string", unsafe.Sizeof(s)},
{"[]int", unsafe.Sizeof(sl)},
{"map[string]int", unsafe.Sizeof(m)},
{"chan int", unsafe.Sizeof(ch)},
{"func()", unsafe.Sizeof(fn)},
{"any", unsafe.Sizeof(in)},
}
}
// Layout reports the size of Padded and Packed.
func Layout() (padded, packed uintptr) {
return unsafe.Sizeof(Padded{}), unsafe.Sizeof(Packed{})
}
// Limits returns the extremes of int64 and uint8 from package math.
func Limits() (maxInt64 int64, minInt64 int64, maxUint8 uint8) {
return math.MaxInt64, math.MinInt64, math.MaxUint8
}
// StringLen shows that len counts bytes and a conversion to []rune counts
// code points.
func StringLen(s string) (bytes, runes int) {
return len(s), len([]rune(s))
}
// ImmutableString shows that changing a byte of a string needs a copy.
func ImmutableString(s string) string {
b := []byte(s) // copy
if len(b) > 0 {
b[0] = 'J'
}
return string(b) // another copy; s itself is unchanged
}Strings and immutability Must-know
In plain words: A string is a read-only sequence of bytes. You can read it, slice it and build a new one, but you cannot change a byte in place.
Common misunderstanding: "len(s) is the number of characters." It is the number of bytes. "世界" has length 6 and two runes. Characters, runes and graphemes are covered in Strings, Runes, fmt Verbs, text/template & regexp.
Definition: the spec states that strings are immutable: "once created, it is impossible to change the contents of a string". []byte(s) and string(b) each copy.
1 s := "john"
2 s[0] = 'J' // compile error: cannot assign to s[0] (neither addressable nor a map index expression)
3 b := []byte(s) // copy: 4 bytes allocated
4 b[0] = 'J'
5 t := string(b) // copy again; s is still "john"Real scenario: building a response in a loop with s += part copies the whole string each time, so a loop over 100 000 parts is quadratic; a strings.Builder or bytes.Buffer is the fix.
Untyped constants and default types Must-know
In plain words: A literal such as 42 or 3.14 and a const declared without a type are exact numbers with no type. They take a type only when you use them.
Common misunderstanding: "const x = 0.1 is a float64." It is an untyped floating-point constant. Written 0.1 + 0.2 as a constant expression it is exactly 0.3; the same sum on two float64 variables is 0.30000000000000004.
Definition: the spec says literal constants, true, false, iota and certain constant expressions are untyped. A constant gets a type explicitly through a declaration or conversion, or implicitly when used in a variable declaration, assignment or as an operand. The default type is bool, rune, int, float64, complex128 or string for the respective kind. Constant expressions are evaluated at compile time and exactly.
1 const a = 15 / 4 // 3 untyped integer constant
2 const b = 15 / 4.0 // 3.75 untyped floating-point constant
3 const Theta float64 = 3/2 // 1.0 integer division first, then typed
4 const Pi float64 = 3/2.// 1.5
5 x := 'x' + 1 // 121 rune (int32) default type
6 var f float64 = 1 << 100 // fine: the exact constant fits a float64Real scenario: time.Sleep(2 * time.Second) works because 2 is untyped and becomes a time.Duration; n := 2; time.Sleep(n * time.Second) does not compile because n is an int. A percentage computed as 100 * done / total with integer variables truncates to 0 until done equals total.
| Literal | Kind | Default type in := |
|---|---|---|
42, 0x2A, 0b101010, 0o52, 1_000_000 | integer | int |
3.14, 1e9, 0x1p-2 | floating-point | float64 |
'x', '世' | rune | rune (int32) |
1i, 2.5 + 3i | complex | complex128 |
"go", `raw` | string | string |
true, false | boolean | bool |
| Operation on untyped operands | Result kind |
|---|---|
| integer op integer | integer (division truncates) |
| integer op floating-point | floating-point |
| rune op integer | rune |
| any op complex | complex |
| comparison | untyped boolean |
| shift with untyped left operand | integer constant |
// Package consts shows untyped constants, exact constant arithmetic,
// default types and the iota patterns that are not enums of strings.
package consts
import (
"fmt"
"math"
)
// Huge needs 101 bits; it is legal because constants are exact and untyped.
const Huge = 1 << 100
// Four is a typed constant derived from Huge; it must fit int8.
const Four int8 = Huge >> 98
// ByteSize is a defined type so iota values print with units.
type ByteSize float64
// The blank identifier skips iota 0; each later line repeats the expression.
const (
_ = iota
KB ByteSize = 1 << (10 * iota)
MB
GB
)
// Weekday starts at 1 on purpose: the zero value means "not set".
type Weekday uint8
// Days of the week, Monday first.
const (
_ Weekday = iota
Monday
Tuesday
Wednesday
)
// Mixed shows two iota uses on one line: both see the same iota.
const (
A, B = iota, iota * 10 // 0, 0
C, D // 1, 10
)
// DefaultTypes returns the %T of each literal kind when it lands in :=.
func DefaultTypes() []string {
i := 42
f := 3.14
r := 'x'
c := 1i
s := "go"
b := true
return []string{
fmt.Sprintf("%T", i), fmt.Sprintf("%T", f), fmt.Sprintf("%T", r),
fmt.Sprintf("%T", c), fmt.Sprintf("%T", s), fmt.Sprintf("%T", b),
}
}
// Divisions shows that the kind of the operands, not the target, decides
// between integer and float division for constants.
func Divisions() (intDiv int, floatDiv float64, typedFloat float64, typedInt float64) {
const a = 15 / 4 // untyped integer constant: 3
const b = 15 / 4.0 // untyped floating-point constant: 3.75
const theta float64 = 3 / 2
const pi float64 = 3 / 2.
return a, b, theta, pi
}
// FloatSum compares exact constant arithmetic with float64 arithmetic.
func FloatSum() (constant, runtime float64) {
const c = 0.1 + 0.2 // exact 0.3, rounded once to float64 on use
x, y := 0.1, 0.2
return c, x + y // 0.3 and 0.30000000000000004
}
// MaxUint64AsUntyped returns math.MaxUint64 after a shift, which only works
// because the constant is untyped until it meets a uint64.
func MaxUint64AsUntyped() uint64 {
const m = 1<<64 - 1
return m
}
// SecondsToDuration shows typed and untyped constants meeting a typed value.
func SecondsToDuration(n int) int64 {
const ns = 1000 * 1000 * 1000 // untyped; fits int64 and int
return int64(n) * ns
}
// LargestSafeInt is math.MaxInt written without the package.
func LargestSafeInt() int {
return int(^uint(0) >> 1)
}
// MathConstants returns a few constants from package math.
func MathConstants() (float64, float64, int64) {
return math.Pi, math.MaxFloat64, math.MaxInt64
}Typed constants, overflow and constant expressions Must-know
In plain words: A typed constant carries a fixed type and must fit it; the compiler refuses a constant that does not fit, but a variable that overflows at run time just wraps.
Common misunderstanding: "Overflow is a run-time panic in Go." Integer overflow at run time wraps silently; only constants are checked, at compile time.
Definition: the spec requires that "the values of typed constants must always be accurately representable by values of the constant type", so uint(-1) and int(3.14) are illegal constant conversions. The divisor of a constant division must not be zero.
1 const Huge = 1 << 100 // ok, untyped
2 const Four int8 = Huge >> 98 // ok: 4 fits int8
3 var a int8 = 200 // compile error: ... (overflows)
4 const d = int32(1) << 33 // compile error: constant 8589934592 overflows int32
5 x := 255; y := uint8(x + 1) // x + 1 is int 256; uint8(256) at run time wraps to 0Real scenario: sizing a buffer with const MaxBody = 10 << 20 is clearer than 10485760; a limit written as const Limit int8 = 130 stops the build instead of failing in production.
| Case | When it is checked | Result |
|---|---|---|
| Constant too big for the declared type | Compile time | Build error (overflows) |
| Typed constant arithmetic out of range | Compile time | constant ... overflows int32 |
| Variable arithmetic out of range | Run time | Wraps silently |
| Float constant converted to integer with a fraction | Compile time | cannot convert 3.14 (untyped float constant) to type int |
| Float variable converted to integer out of range | Run time | Implementation-dependent value |
var versus := versus const Must-know
In plain words: var declares a variable anywhere, := is a shorthand for declaring and initialising inside a function, and const declares an immutable compile-time value.
Common misunderstanding: ":= assigns." It declares at least one new variable in the current scope, and assigns the others only if they were declared in the same scope.
Definition: var x T uses the zero value; var x = e infers the type from e's default type; x := e is only allowed in function bodies and needs at least one new name on the left; a package-level declaration cannot use :=.
1 var a int // 0
2 var b = 2.5 // float64
3 c := "go" // string
4 var d, e = 1, "x" // int and string
5 f, err := os.Open("x") // declares f and err
6 g, err := os.Open("y") // declares g, reuses err in the same scope
7 const h = 1 << 10 // compile-timeReal scenario: a package-level var ErrNotFound = errors.New("not found") is a sentinel; a package-level var cache = map[string]int{} is shared mutable state that needs a mutex; configuration defaults belong in const groups.
| Form | Where | Type | Zero value? |
|---|---|---|---|
var x T | Anywhere | T | Yes |
var x = e | Anywhere | Default type of e | No, set by e |
x := e | Function bodies only | Default type of e | No |
const x = e | Anywhere | Untyped or typed | Not a variable |
x, y = y, x | Function bodies | Existing variables | n/a |
Shadowing Must-know
In plain words: If you write name, err := ... inside an if or for block, Go creates new variables that hide the outer name and err until the block ends.
Common misunderstanding: "The compiler will warn me." It does not; the program is valid. go vet does not check it by default either. The shadow analyzer is a separate tool: the Go 1.12 release notes say the experimental -shadow option is no longer available in go vet and the check can be run with go vet -vettool=$(which shadow).
Definition: a declaration in an inner block hides an identically named identifier in an outer block (lexical scope, see Scope and blocks).
1 name := "fallback"
2 if key != "" {
3 name, err := lookup(key) // NEW name and err
4 if err != nil { return "error" }
5 _ = name
6 }
7 return name // still "fallback"Real scenario: the classic production bug is ctx, cancel := context.WithTimeout(...) or db, err := open() inside an if so the outer db stays nil and the next call panics with invalid memory address or nil pointer dereference. Bare return with shadowed named results does not compile: result parameter err not in scope at return.
| Cause | Symptom | Fix |
|---|---|---|
x, err := f() inside a block while x is outer | Outer x unchanged | Declare var err error and use x, err = f() |
if v, ok := m[k]; ok {} | Fine: scoped on purpose | Keep it, v and ok are only needed inside |
Named result shadowed, bare return | Compile error | Assign with = |
Loop for _, x := range xs inside a function with x | Outer x hidden | Rename one |
// Package shadowing shows how := in an inner block hides an outer variable,
// and the fixes.
package shadowing
import "errors"
var errNotFound = errors.New("not found")
func lookup(key string) (string, error) {
if key == "primary" {
return "db-1", nil
}
return "", errNotFound
}
// PickBuggy intends to overwrite name when the lookup succeeds. The := in
// the if block declares a NEW name, so the outer one never changes.
func PickBuggy(key string) string {
name := "fallback"
if key != "" {
name, err := lookup(key) // shadows name and err
if err != nil {
return "error"
}
_ = name // compiles because the shadow is "used"
}
return name // still "fallback"
}
// PickFixed declares err once and assigns with = so the outer name is set.
func PickFixed(key string) string {
name := "fallback"
if key != "" {
var err error
name, err = lookup(key)
if err != nil {
return "error"
}
}
return name
}
// LoopClosures collects the loop variable seen by each closure. Since Go 1.22
// (go.mod says go 1.22 or later) every iteration has its own variable, so the
// result is 0, 1, 2 instead of 3, 3, 3.
func LoopClosures() []int {
var fns []func() int
for i := 0; i < 3; i++ {
fns = append(fns, func() int { return i })
}
out := make([]int, 0, len(fns))
for _, f := range fns {
out = append(out, f())
}
return out
}
// Scopes demonstrates block scope: the same name in nested blocks.
func Scopes() []int {
x := 1
out := []int{x}
{
x := 2 // new variable in an explicit block
out = append(out, x)
}
if x := 3; x > 2 { // scoped to the if statement
out = append(out, x)
}
switch x := 4; {
case x > 3:
out = append(out, x)
}
return append(out, x) // the outer x is still 1
}
// MultiAssign shows the swap idiom and that the right side is evaluated
// before any assignment happens.
func MultiAssign() (a, b int, fib []int) {
a, b = 1, 2
a, b = b, a // swap
x, y := 0, 1
for range 6 {
fib = append(fib, x)
x, y = y, x+y
}
return a, b, fib
}Zero values Must-know
In plain words: Every variable you declare without a value starts as the "empty" value of its type: 0, false, "", or nil. Good Go types are designed so that this empty value already works.
Common misunderstanding: "A nil map or nil slice is broken." A nil slice can be appended to, ranged over and measured; reading a nil map returns the zero value. Only writing to a nil map panics.
Definition: the spec: when storage is allocated "the variable or value is given a default value. Each element of such a variable or value is set to the zero value for its type: false for booleans, 0 for numeric types, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps." This is recursive for arrays and structs.
1 var c Counter // sync.Mutex inside is unlocked, map is nil
2 c.Inc("a") // lazily make(map) under the lock
3 var buf bytes.Buffer // "the zero value for Buffer is an empty buffer ready to use"
4 buf.WriteString("x")
5 var m map[string]int
6 m["k"] = 1 // panic: assignment to entry in nil mapReal scenario: a sync.WaitGroup, sync.Mutex, bytes.Buffer, strings.Builder and http.Client all work as zero values; a Config{} with Port == 0 meaning "use the default" is a common option pattern; a time.Time{} is January 1, year 1 and IsZero() reports it.
| Type | Zero value | Safe to use? |
|---|---|---|
int, float64 | 0 | Yes |
string | "" | Yes |
bool | false | Yes |
| pointer | nil | Reading through it panics |
| slice | nil (len 0, cap 0) | Yes: append, range, len |
| map | nil | Read yes, write panics |
| channel | nil | Send and receive block forever |
| func | nil | Calling it panics |
| interface | nil (no type, no value) | Calling a method panics |
| struct, array | Every field or element zeroed | Depends on the fields |
// Package zeroval shows zero values and types designed so that the zero
// value is ready to use.
package zeroval
import (
"bytes"
"fmt"
"sync"
)
// Counter needs no constructor: the zero Mutex is unlocked and the map is
// created on first write.
type Counter struct {
mu sync.Mutex
n map[string]int
}
// Inc adds one to key.
func (c *Counter) Inc(key string) {
c.mu.Lock()
defer c.mu.Unlock()
if c.n == nil {
c.n = make(map[string]int)
}
c.n[key]++
}
// Get reads key; reading a nil map is safe and yields 0.
func (c *Counter) Get(key string) int {
c.mu.Lock()
defer c.mu.Unlock()
return c.n[key]
}
// Zero lists the zero value of each basic kind, formatted with %#v.
func Zero() map[string]string {
var (
i int
f float64
b bool
s string
p *int
sl []int
m map[string]int
ch chan int
fn func()
e error
ar [2]bool
st struct {
N int
S string
}
)
return map[string]string{
"int": fmt.Sprintf("%#v", i), "float64": fmt.Sprintf("%#v", f),
"bool": fmt.Sprintf("%#v", b), "string": fmt.Sprintf("%#v", s),
"*int": fmt.Sprintf("%#v", p), "[]int": fmt.Sprintf("%#v", sl),
"map": fmt.Sprintf("%#v", m), "chan": fmt.Sprintf("%#v", ch),
"func": fmt.Sprintf("%#v", fn == nil), "error": fmt.Sprintf("%#v", e),
"[2]bool": fmt.Sprintf("%#v", ar), "struct": fmt.Sprintf("%#v", st),
}
}
// NilSliceIsUsable appends to, ranges over and measures a nil slice.
func NilSliceIsUsable() (before, after int) {
var s []int
for range s { // zero iterations
}
before = len(s)
s = append(s, 1, 2)
return before, len(s)
}
// BufferZero writes into a bytes.Buffer without initialising it.
func BufferZero() string {
var buf bytes.Buffer
buf.WriteString("ready ")
buf.WriteString("to use")
return buf.String()
}
// WriteNilMap recovers from the panic caused by assigning into a nil map and
// returns the panic text.
func WriteNilMap() (msg string) {
defer func() {
if r := recover(); r != nil {
msg = fmt.Sprint(r)
}
}()
var m map[string]int
m["k"] = 1
return ""
}
// Config uses the zero value as "not set" with explicit defaults applied once.
type Config struct {
Port int
Host string
Verbose bool
}
// WithDefaults fills the fields that are still zero.
func (c Config) WithDefaults() Config {
if c.Port == 0 {
c.Port = 8080
}
if c.Host == "" {
c.Host = "localhost"
}
return c
}nil, untyped nil and typed nil Must-know
In plain words: An interface variable holds two things: a type and a value. It is nil only when both are empty. Returning a nil pointer through an interface gives a non-nil interface.
Common misunderstanding: "If the pointer inside is nil, the interface is nil." The Go FAQ explains: if we store a nil pointer of type *int inside an interface value, the inner type will be *int regardless of the value of the pointer, "(T=*int, V=nil)". Such an interface value will therefore be non-nil.
Definition: untyped nil is the predeclared identifier that can be assigned to pointers, functions, interfaces, slices, maps and channels. A typed nil is a nil pointer (or slice, map, channel) of a concrete type; stored in an interface it makes the interface non-nil.
1 func mayFail(fail bool) error {
2 var e *MyErr // typed nil pointer
3 if fail { e = &MyErr{} }
4 return e // interface (T=*MyErr, V=nil) when fail is false
5 }
6 err := mayFail(false)
7 err != nil // true! the call succeededReal scenario: a repository function returns a concrete *NotFoundError through error; a middleware sees err != nil and answers 500 on every request. staticcheck reports SA4023 for impossible comparisons of an interface with untyped nil and SA4022 for &x == nil.
| Kind | x == nil allowed | Behaviour when nil |
|---|---|---|
| pointer | yes | Dereference panics: invalid memory address or nil pointer dereference |
| slice | yes | len 0, append works |
| map | yes | Read gives zero value, write panics |
| channel | yes | Send and receive block forever; close panics |
| func | yes | Call panics |
| interface | yes | Method call panics; nil only if type and value are unset |
| struct, int, string | no | Not nilable |
// Package nilness shows nil for each kind, the typed-nil interface trap,
// and the difference between conversions and type assertions.
package nilness
import "fmt"
// MyErr is an error with a pointer receiver.
type MyErr struct{ Code int }
func (e *MyErr) Error() string { return fmt.Sprintf("my error %d", e.Code) }
// MayFailBuggy returns a typed nil: the interface holds (type *MyErr, value nil),
// so the caller's err != nil is true even on success.
func MayFailBuggy(fail bool) error {
var e *MyErr
if fail {
e = &MyErr{Code: 7}
}
return e
}
// MayFail returns the untyped nil interface on success.
func MayFail(fail bool) error {
if fail {
return &MyErr{Code: 7}
}
return nil
}
// Kinds reports which kinds of value can be compared with nil and what len
// says for each when nil.
func Kinds() map[string]string {
var (
p *int
sl []int
m map[string]int
ch chan int
fn func()
in any
)
return map[string]string{
"pointer": fmt.Sprint(p == nil),
"slice": fmt.Sprint(sl == nil, len(sl), cap(sl)),
"map": fmt.Sprint(m == nil, len(m), m["x"]),
"chan": fmt.Sprint(ch == nil),
"func": fmt.Sprint(fn == nil),
"interface": fmt.Sprint(in == nil),
}
}
// Describe uses the comma-ok form of a type assertion; it never panics.
func Describe(x any) string {
if s, ok := x.(string); ok {
return "string " + s
}
if n, ok := x.(int); ok {
return fmt.Sprint("int ", n)
}
if err, ok := x.(error); ok { // assertion to an interface type
return "error " + err.Error()
}
return fmt.Sprintf("other %T", x)
}
// MustInt uses the single-value form, which panics when x is not an int.
func MustInt(x any) (n int, msg string) {
defer func() {
if r := recover(); r != nil {
msg = fmt.Sprint(r)
}
}()
return x.(int), ""
}
// Convert shows conversions: they are checked at compile time and work between
// types with the same underlying type or between numeric types.
func Convert() (float64, []byte, string) {
i := 3
return float64(i), []byte("go"), string([]rune{0x4e16, 0x754c})
}Conversions versus type assertions Must-know
In plain words: A conversion T(x) changes a value to another type at compile time. A type assertion x.(T) asks an interface what is inside at run time.
Common misunderstanding: "x.(T) converts x to T." It cannot convert; it only unwraps. If x holds a string, x.(int) panics rather than parsing it.
Definition: a conversion is legal between types with identical underlying types and between numeric types, string and []byte/[]rune, and so on. A type assertion needs an interface operand; the single-value form panics on failure, the comma-ok form v, ok := x.(T) returns ok == false. Interface-to-interface assertion checks the method set.
1 var i any = "go"
2 n := i.(int) // panic: interface conversion: interface {} is string, not int
3 s, ok := i.(string) // s == "go", ok == true
4 _, ok = i.(int) // ok == false, no panic
5 f := float64(7) // conversion: 7.0
6 u := uint8(300) // compile error: constant 300 overflows uint8Real scenario: decoding JSON into any gives float64 for every number, so v.(int) panics, while int(v.(float64)) works; a handler that receives any from a context value must use the comma-ok form. Details are in Interfaces, Type Assertions, Type Switches & any.
| Operation | Checked | Failure |
|---|---|---|
T(x) with constant x | Compile time | Build error |
T(x) numeric, variable x | Never | Truncation or wrap-around |
string(rune), []byte(s) | Compile time | Copy, no error |
x.(T) | Run time | Panic |
v, ok := x.(T) | Run time | ok == false |
switch x.(type) | Run time | Falls to default |
Numeric conversion traps Must-know
In plain words: Converting between number types never raises an error: the bits are cut, the fraction is dropped or the sign is reinterpreted.
Common misunderstanding: "Go would stop me if the value did not fit." Only for constants. For variables, int8(200) is -56, uint(-1) is 18446744073709551615 on 64-bit, and int(2.99) is 2.
Definition: float to integer conversion truncates toward zero; the spec says that in non-constant conversions involving floating-point values, if the result type cannot represent the value the conversion succeeds but the result is implementation-dependent. Integer division truncates toward zero and % takes the sign of the dividend.
1 int8(200) // -56
2 uint(-1) // 18446744073709551615 (variable operand)
3 int(-2.99) // -2
4 -7 / 2 // -3
5 -7 % 2 // -1
6 x := math.MaxInt64; x++ // -9223372036854775808Real scenario: uint(len(items) - 1) on an empty slice becomes a huge index; a duration from time.Duration(seconds * float64(time.Second)) loses nanoseconds; an invoice total in float64 adds 0.1 + 0.2 and fails an equality check.
| Trap | Example | Safe version |
|---|---|---|
| Truncation | int(f) | int(math.Round(f)) after a range check |
| Narrowing | int32(x) | Check x >= math.MinInt32 && x <= math.MaxInt32 |
| Signed to unsigned | uint(i) with i < 0 | Reject negatives first |
| Overflow | a + b on int64 | Compare against the limit before adding |
| Text from number | string(65) | strconv.Itoa(65) or string(rune(65)); vet flags it |
// Package convert shows numeric conversions that lose information and the
// checked versions that refuse to.
package convert
import (
"errors"
"fmt"
"math"
"strconv"
)
// ErrOverflow is returned when a value does not fit the target type.
var ErrOverflow = errors.New("value out of range")
// Truncate drops the fraction (it does not round).
func Truncate(f float64) int { return int(f) }
// WrapInt8 converts without checking: 200 becomes -56.
func WrapInt8(i int) int8 { return int8(i) }
// NegativeToUint converts a negative int to uint and wraps to a huge value.
func NegativeToUint(i int) uint { return uint(i) }
// ToInt32 converts and reports overflow instead of wrapping.
func ToInt32(i int64) (int32, error) {
if i < math.MinInt32 || i > math.MaxInt32 {
return 0, fmt.Errorf("convert %d to int32: %w", i, ErrOverflow)
}
return int32(i), nil
}
// ToUint converts a signed value and rejects negatives.
func ToUint(i int) (uint, error) {
if i < 0 {
return 0, fmt.Errorf("convert %d to uint: %w", i, ErrOverflow)
}
return uint(i), nil
}
// AddInt64 adds two int64 values and reports signed overflow.
func AddInt64(a, b int64) (int64, bool) {
sum := a + b // wraps silently on overflow
if (b > 0 && sum < a) || (b < 0 && sum > a) {
return 0, false
}
return sum, true
}
// WrapAround increments the largest int64 at runtime; the compiler would
// reject math.MaxInt64 + 1 as a constant expression.
func WrapAround() int64 {
x := int64(math.MaxInt64)
x++
return x
}
// Division shows that integer division truncates toward zero and that the
// remainder takes the sign of the dividend.
func Division(a, b int) (quo, rem int) { return a / b, a % b }
// Reinterpret converts a byte to the rune with the same number and the digit
// text for an int; string(int) is a vet error because it is almost never
// what the author meant.
func Reinterpret(i int) (asRune, asText string) {
return string(rune(i)), strconv.Itoa(i)
}
// Parse shows that parsing is the checked way to go from text to numbers.
func Parse(s string) (int8, error) {
n, err := strconv.ParseInt(s, 10, 8)
return int8(n), err
}
// FloatToInt converts a float that is in range; behaviour for NaN or values
// outside the range of int is implementation-specific per the spec.
func FloatToInt(f float64) (int, error) {
if math.IsNaN(f) || f < math.MinInt64 || f >= math.MaxInt64 {
return 0, fmt.Errorf("convert %v to int: %w", f, ErrOverflow)
}
return int(f), nil
}iota Must-know
In plain words: iota is a counter that starts at 0 on the first line of a const (...) block and goes up by one on every line.
Common misunderstanding: "iota is a global counter." It resets to 0 in every const block and counts lines (specs), not names: two names on the same line see the same value.
Definition: the spec: within a constant declaration iota is an untyped integer constant equal to the index of the ConstSpec in the block; an omitted expression list repeats the previous list and its type. The blank identifier skips a value.
1 const (
2 _ = iota // 0, skipped
3 KB ByteSize = 1 << (10 * iota) // 1024
4 MB // 1 << 20
5 GB // 1 << 30
6 )Real scenario: ByteSize in Effective Go; HTTP method codes; log levels; weekday numbers where 0 is "unset"; state machine states.
| Pattern | Code | Values |
|---|---|---|
| Plain sequence | A = iota then B, C | 0, 1, 2 |
| Skip zero | _ = iota then A | A is 1 |
| Start at 1 | A = iota + 1 | 1, 2, 3 |
| Powers of two | A = 1 << iota | 1, 2, 4, 8 |
| Units | KB = 1 << (10 * iota) | 1024, 1048576 |
| Skip a value | _ between names | Gap in the numbering |
| Two names per line | A, B = iota, iota * 10 | Same iota on the line |
Enums Must-know
In plain words: Go has no enum keyword. You make one from a named integer type, a block of constants with iota, and a String() method.
Common misunderstanding: "An enum type only holds its listed values." Status(42) compiles and prints as Status(42). The enum is a convention, so you add a validity check and a safe zero value.
Definition: the pattern is type Status uint8, const (StatusUnknown Status = iota; StatusPending; ...), an unexported statusEnd sentinel for range checks, a generated String() (stringer), ParseStatus for text and an exhaustive switch.
1 type Status uint8
2 const ( StatusUnknown Status = iota; StatusPending; StatusPaid; ... ; statusEnd )
3 //go:generate stringer -type=Status -linecomment
4 go generate ./... -> writes status_string.go
5 fmt.Println(StatusPaid) // paid
6 fmt.Println(Status(42)) // Status(42)Real scenario: an order status stored in a database and returned by an API. If the zero value were Pending, a struct with a forgotten field would look like a legitimate pending order. With StatusUnknown at 0, validation rejects it.
| Decision | Recommended | Why |
|---|---|---|
| Underlying type | uint8 or int | Small, comparable, cheap to store |
| Value 0 | An explicit Unknown/Invalid | The zero value is the "unset" value |
| Numbering | Never renumber stored values | Reordering the block changes persisted meaning |
String() | stringer -linecomment | No hand-written table to drift |
| Switches | List every constant, default returns an error | A new constant fails loudly |
| Linter | exhaustive (via golangci-lint) | Reports a switch that misses a constant |
stringer is the code generator from golang.org/x/tools/cmd/stringer; given a signed or unsigned integer type with constants it creates a String() method that returns the constant's name, or with -linecomment the line comment. Its source states the generated file works best with constants that are consecutive values such as created using iota.
// Package enum shows iota enums: a skip-zero sentinel, generated String,
// parsing, an exhaustive switch, text/JSON and SQL marshalling, and bit flags.
package enum
import (
"database/sql/driver"
"errors"
"fmt"
)
// Status is an order status. The zero value is deliberately invalid, so a
// forgotten field cannot be mistaken for a real state.
type Status uint8
//go:generate stringer -type=Status -linecomment
// Statuses. statusEnd is unexported and marks the end for range checks.
const (
StatusUnknown Status = iota // unknown
StatusPending // pending
StatusPaid // paid
StatusShipped // shipped
StatusCancelled // cancelled
statusEnd
)
// ErrInvalidStatus is returned for names or numbers outside the enum.
var ErrInvalidStatus = errors.New("invalid status")
// Valid reports whether s is one of the real statuses.
func (s Status) Valid() bool { return s > StatusUnknown && s < statusEnd }
// ParseStatus converts the text form back to a Status.
func ParseStatus(name string) (Status, error) {
for s := StatusPending; s < statusEnd; s++ {
if s.String() == name {
return s, nil
}
}
return StatusUnknown, fmt.Errorf("parse %q: %w", name, ErrInvalidStatus)
}
// MarshalText makes encoding/json and encoding/xml write the name, and
// refuses to write an invalid value.
func (s Status) MarshalText() ([]byte, error) {
if !s.Valid() {
return nil, fmt.Errorf("marshal %d: %w", uint8(s), ErrInvalidStatus)
}
return []byte(s.String()), nil
}
// UnmarshalText is the inverse of MarshalText.
func (s *Status) UnmarshalText(b []byte) error {
v, err := ParseStatus(string(b))
if err != nil {
return err
}
*s = v
return nil
}
// Value stores the name in a text column (database/sql/driver.Valuer).
func (s Status) Value() (driver.Value, error) {
if !s.Valid() {
return nil, fmt.Errorf("value %d: %w", uint8(s), ErrInvalidStatus)
}
return s.String(), nil
}
// Scan reads the name from a text column (database/sql.Scanner).
func (s *Status) Scan(src any) error {
switch v := src.(type) {
case string:
return s.UnmarshalText([]byte(v))
case []byte:
return s.UnmarshalText(v)
case nil:
*s = StatusUnknown
return nil
default:
return fmt.Errorf("scan %T into Status: %w", src, ErrInvalidStatus)
}
}
// CanCancel is an exhaustive switch: every constant is listed, and the
// default branch makes a newly added constant fail loudly instead of
// silently falling through. Linters such as exhaustive check the list.
func CanCancel(s Status) (bool, error) {
switch s {
case StatusPending, StatusPaid:
return true, nil
case StatusShipped, StatusCancelled:
return false, nil
case StatusUnknown:
return false, fmt.Errorf("can cancel: %w", ErrInvalidStatus)
default:
return false, fmt.Errorf("can cancel %d: %w", uint8(s), ErrInvalidStatus)
}
}
// All returns every valid status in declaration order.
func All() []Status {
out := make([]Status, 0, statusEnd-1)
for s := StatusPending; s < statusEnd; s++ {
out = append(out, s)
}
return out
}// Code generated by "stringer -type=Status -linecomment"; DO NOT EDIT.
package enum
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[StatusUnknown-0]
_ = x[StatusPending-1]
_ = x[StatusPaid-2]
_ = x[StatusShipped-3]
_ = x[StatusCancelled-4]
_ = x[statusEnd-5]
}
const _Status_name = "unknownpendingpaidshippedcancelledstatusEnd"
var _Status_index = [...]uint8{0, 7, 14, 18, 25, 34, 43}
func (i Status) String() string {
idx := int(i) - 0
if i < 0 || idx >= len(_Status_index)-1 {
return "Status(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _Status_name[_Status_index[idx]:_Status_index[idx+1]]
}Bit flags Important
In plain words: A bit flag packs several yes/no options into one integer, one bit per option.
Common misunderstanding: "Flags can be an ordinary sequential enum." Sequential values (0, 1, 2, 3) overlap in binary; flag constants must be powers of two so they combine without collisions.
Definition: 1 << iota gives 1, 2, 4. Test with p & q == q, set with |, clear with &^ (AND NOT).
1 p := PermRead | PermWrite // 0b011
2 p & PermWrite == PermWrite // true
3 p &^ PermRead // 0b010
4 Perm(8).Valid() // false: bit outside PermAllReal scenario: file permission bits, feature flags in a token, role sets in a JWT, os.O_RDWR|os.O_CREATE open flags.
| Operator | Meaning | Use |
|---|---|---|
| | OR | Set bits |
& | AND | Test bits |
&^ | AND NOT | Clear bits |
^ | XOR or NOT | Toggle bits |
<< >> | Shift | Build constants |
package enum
import "strings"
// Perm is a set of permission bits.
type Perm uint8
// Each constant is one bit: 1, 2, 4.
const (
PermRead Perm = 1 << iota
PermWrite
PermDelete
)
// PermAll is the union of every defined bit.
const PermAll = PermRead | PermWrite | PermDelete
// Has reports whether every bit in q is set in p.
func (p Perm) Has(q Perm) bool { return p&q == q }
// With returns p with the bits of q set.
func (p Perm) With(q Perm) Perm { return p | q }
// Without returns p with the bits of q cleared (AND NOT).
func (p Perm) Without(q Perm) Perm { return p &^ q }
// Valid reports whether p has no bit outside PermAll.
func (p Perm) Valid() bool { return p&^PermAll == 0 }
// String lists the names of the set bits.
func (p Perm) String() string {
if p == 0 {
return "none"
}
var parts []string
for _, f := range []struct {
bit Perm
name string
}{{PermRead, "read"}, {PermWrite, "write"}, {PermDelete, "delete"}} {
if p.Has(f.bit) {
parts = append(parts, f.name)
}
}
if !p.Valid() {
parts = append(parts, "unknown")
}
return strings.Join(parts, "|")
}Enum marshalling: JSON, text and SQL Important
In plain words: An integer enum would be written as 2 in JSON and in the database. Implement encoding.TextMarshaler and TextUnmarshaler so JSON carries the name, and driver.Valuer and sql.Scanner for SQL.
Common misunderstanding: "Renaming a constant is harmless." Persisted names are part of your API. Numbers or names that were written to a database, a queue or a JSON document are a contract; see Message Design & Schema Evolution and API Versioning.
Definition: encoding/json uses MarshalText for a value that implements encoding.TextMarshaler. Go 1.24 added the omitzero tag option, which omits a field whose value is the zero value, so a zero StatusUnknown can be left out of the JSON.
1 json.Marshal(order{Status: StatusPaid}) -> {"id":1,"status":"paid"}
2 json.Marshal(order{ID: 2}) -> {"id":2} (omitzero drops Unknown)
3 json.Marshal(order{Status: Status(77)}) -> error: marshal 77: invalid status
4 json.Unmarshal(`"lost"`, &s) -> error: parse "lost": invalid statusReal scenario: the same order status is read by a Go service, a PHP service and a dashboard; the string form is stable across languages, an integer is not.
| Layer | Interface | Stored as |
|---|---|---|
| JSON, XML | encoding.TextMarshaler / TextUnmarshaler | Name string |
database/sql write | driver.Valuer | text column or a Postgres enum |
database/sql read | sql.Scanner | Same |
| Protocol Buffers | Generated enum, number 0 must be the default | Number |
| Logs | fmt.Stringer | Name |
-- Storing the enum by name: readable, safe to reorder in Go, validated by the database
CREATE TABLE orders (
id bigint PRIMARY KEY,
status text NOT NULL CHECK (status IN ('pending', 'paid', 'shipped', 'cancelled'))
);
-- Postgres alternative: CREATE TYPE order_status AS ENUM (...); ALTER TYPE ... ADD VALUE is cheap, removal is not.Named types and type aliases Important
In plain words: type UserID int64 creates a new type that cannot be mixed with int64 or OrderID without a conversion. type OldID = UserID only gives another name to the same type.
Common misunderstanding: "An alias and a named type are the same thing." A defined type has its own method set and identity; an alias is identical to the original and exists mainly for gradual refactoring and type renames.
Definition: the spec: an alias declaration binds an identifier to the given type; within its scope it serves as an alias for the given type. Go 1.24 supports parameterised aliases. byte, rune and any are predeclared aliases.
1 type UserID int64 // defined type
2 type OldID = UserID // alias
3 var u UserID = 5 // ok, 5 is untyped
4 var n int64 = 5; u = n // compile error: cannot use n (variable of type int64) as UserID value
5 u = UserID(n) // explicit conversion
6 type Set[T comparable] = map[T]struct{} // Go 1.24 generic aliasReal scenario: UserID and OrderID stop a function Cancel(user, order) being called with swapped arguments; Celsius and Fahrenheit stop unit mistakes; an alias lets you move a type to another package without breaking callers.
| Aspect | Defined type type A B | Alias type A = B |
|---|---|---|
| Identity | New, distinct from B | Identical to B |
| Methods | Own method set, none inherited from B | Methods of B |
Assignable from B | Only with conversion (or untyped constant) | Yes |
%T prints | pkg.A | pkg.B |
| Use | Domain types, units, enums | Refactoring, renames, short names |
// Package alias shows defined types versus aliases.
package alias
import "fmt"
// UserID is a defined type: new identity, same underlying int64.
type UserID int64
// OrderID is another defined type with the same underlying type; the two
// cannot be mixed without a conversion.
type OrderID int64
// String is a method only UserID has.
func (u UserID) String() string { return fmt.Sprintf("user-%d", int64(u)) }
// OldUserID is an alias: another name for exactly the same type.
type OldUserID = UserID
// Set is a generic alias (Go 1.24).
type Set[T comparable] = map[T]struct{}
// Celsius and Fahrenheit stop a float64 temperature being used as the wrong unit.
type (
Celsius float64
Fahrenheit float64
)
// ToF converts between the two defined types explicitly.
func (c Celsius) ToF() Fahrenheit { return Fahrenheit(c*9/5 + 32) }
// Same reports whether the alias and the original are identical types by
// assigning one to the other without a conversion.
func Same() bool {
var a OldUserID = 5
var u UserID = a // no conversion needed
return u == a
}
// Convert needs explicit conversions between defined types.
func Convert(u UserID) OrderID { return OrderID(u) }
// Untyped constants flow into any defined type with a compatible underlying
// type; typed variables do not.
func Literal() (UserID, OrderID) {
return 7, 7
}
// Add shows that arithmetic is allowed within the defined type.
func Add(a, b UserID) UserID { return a + b }
// NewSet builds a generic alias value.
func NewSet[T comparable](items ...T) Set[T] {
s := make(Set[T], len(items))
for _, it := range items {
s[it] = struct{}{}
}
return s
}
// BuiltinAliases shows that byte, rune and any are aliases.
func BuiltinAliases() (byte, rune, any) {
var b uint8 = 'a'
var r int32 = 'é'
var a interface{} = "x"
return b, r, a
}Scope and blocks Important
In plain words: A name is visible from its declaration to the end of the innermost block { } that contains it, plus nested blocks.
Common misunderstanding: "Every { } is a scope except if and for." if, for, switch and select statements each have their own implicit block, and so does every clause, which is why if x := f(); x > 0 {} makes x visible only there.
Definition: the spec: Go is lexically scoped using blocks: predeclared identifiers are in the universe block, top-level declarations in the package block, imported package names in the file block, and parameters and local variables in the function body block. Since Go 1.22 each iteration of a for loop declares new variables.
1 x := 1
2 { x := 2 } // inner block, new x
3 if x := 3; x > 2 { } // x scoped to the if statement
4 for i := 0; i < 3; i++ { fns = append(fns, func() int { return i }) }
5 // Go 1.22+: closures return 0, 1, 2; before: 3, 3, 3Real scenario: the pre-1.22 loop variable capture bug in go func() { use(i) }(); defer in a loop body; variables declared in a switch initializer. More on loops in Control Flow and Pointers & Memory Model Basics.
| Block | Scope of a name declared in it |
|---|---|
| Universe | Whole program (int, nil, true, len) |
| Package | All files of the package |
| File | The file (import names) |
| Function | Parameters and results to the end of the function |
if/for/switch header | That statement and its branches |
Explicit { } | Up to the closing brace |
case clause | That clause |
Multiple assignment and swap Good to know
In plain words: a, b = b, a swaps two variables with no temporary.
Common misunderstanding: "The assignments happen left to right, so the second sees the first." The spec evaluates the operands on the right and the index and pointer operands on the left first, then assigns in a second phase.
Definition: in a tuple assignment all expressions on both sides are evaluated before any assignment happens, so x, y = y, x+y computes Fibonacci.
1 a, b := 1, 2
2 a, b = b, a // a == 2, b == 1
3 x, y := 0, 1
4 x, y = y, x+y // (1, 1), then (1, 2)
5 i, s[i] = 1, 9 // s[i] uses the OLD iReal scenario: swapping slice elements s[i], s[j] = s[j], s[i]; Fibonacci and Euclid's gcd (a, b = b, a%b); returning two values from a function.
| Form | Meaning |
|---|---|
a, b = b, a | Swap |
a, b := f() | Declare two from a multi-value call |
_, err = f() | Discard a value |
v, ok = m[k] | Comma-ok map read |
v, ok = <-ch | Comma-ok channel receive |
math constants and unsafe.Sizeof Good to know
In plain words: Package math names the limits (math.MaxInt64, math.MaxUint32, math.Pi); unsafe.Sizeof tells you how many bytes a value takes.
Common misunderstanding: "unsafe.Sizeof of a slice or map is the size of its data." It is the size of the header: unsafe.Sizeof of a slice is 24 bytes and of a string 16 bytes on 64-bit, whatever they point to.
Definition: Sizeof takes an expression and returns the size in bytes as a constant of type uintptr; for a struct it includes padding. math limits are untyped constants, so math.MaxInt64 fits int64, and math.MaxUint64 only fits a uint64.
1 unsafe.Sizeof(int8(0)) // 1
2 unsafe.Sizeof("go") // 16 (pointer + length), not 2
3 unsafe.Sizeof([]int{}) // 24 (pointer, length, capacity)
4 unsafe.Sizeof(Padded{}) // 32
5 unsafe.Sizeof(Packed{}) // 16 (same fields, largest first)Real scenario: shrinking a struct that is allocated millions of times by ordering fields largest first; checking that a []int32 of a million entries is 4 MB and not 8; math.MaxInt32 as a PostgreSQL integer limit check.
| Constant | Value | Type of use |
|---|---|---|
math.MaxInt8, MinInt8 | 127, -128 | Range checks |
math.MaxInt32 | 2147483647 | PostgreSQL integer ceiling |
math.MaxInt64 | 9223372036854775807 | bigint ceiling |
math.MaxUint32 | 4294967295 | IPv4 as a number |
math.MaxInt | MaxInt32 or MaxInt64 | Platform limit |
math.Pi, math.E | Untyped floats | Geometry |
math.MaxFloat64 | about 1.8e308 | Largest finite float64 |
go vet and staticcheck findings Important
In plain words: go vet ships with Go and runs a fixed set of checks; staticcheck is a separate linter with hundreds of checks. Run both in CI.
Common misunderstanding: "go vet finds shadowing." Not by default; shadow is an additional analyzer.
Definition: go vet ./... includes stringintconv, copylocks, printf, loopclosure and unusedresult. staticcheck classes: SA (correctness), S (simplifications), ST (style), QF (quick fixes).
1 $ go vet ./...
2 ./x.go:7:7: conversion from int to string yields a string of one rune, not a string of digits
3 $ go vet -vettool=$(which shadow) ./...
4 shadowing.go:21:3: declaration of "name" shadows declaration at line 19
5 $ staticcheck ./...
6 x.go:12:5: SA4003: ... (comparing an unsigned value against a negative one)Real scenario: a CI step go vet ./... && staticcheck ./... catches string(i), impossible comparisons, a typed constant list with a missing type (SA9004) and ineffective assignments (SA4006).
| Check | Tool | Finds |
|---|---|---|
stringintconv | go vet | string(i) for an integer i |
| shadow | shadow vettool | Inner := hiding an outer variable |
| SA4003 | staticcheck | Comparing unsigned with a negative constant |
| SA4022, SA4023 | staticcheck | &x == nil, impossible interface-to-nil comparison |
| SA4006 | staticcheck | Value assigned and never read |
| SA9004 | staticcheck | Only the first constant of a group has an explicit type |
| ST1012 | staticcheck | Error variable not named errFoo |
exhaustive | golangci-lint | Switch over an enum that misses a constant |
Mechanics
Exact messages and what they mean Must-know
All messages below were produced by Go 1.27.4 on this machine (compiler, go vet, the shadow tool) or are the documented runtime text.
| Message | Where it comes from | Fix |
|---|---|---|
cannot use 200 (untyped int constant) as int8 value in variable declaration (overflows) | Compiler | Use a wider type |
cannot use -1 (untyped int constant) as uint value in variable declaration (overflows) | Compiler | Reject negatives earlier |
cannot use big (untyped int constant 1267650600228229401496703205376) as int value in variable declaration (overflows) | Compiler | Use math/big or float64 |
int32(1) << 33 (constant 8589934592 of type int32) overflows int32 | Compiler | Widen the type before shifting |
invalid operation: x + y (mismatched types int and float64) | Compiler | Convert one operand |
declared and not used: err | Compiler | Use or _ |
result parameter err not in scope at return | Compiler | Avoid shadowing named results |
conversion from int to string yields a string of one rune, not a string of digits | go vet | strconv.Itoa |
declaration of "name" shadows declaration at line 19 | shadow tool | Use = |
panic: assignment to entry in nil map | Runtime | make the map |
panic: interface conversion: interface {} is string, not int | Runtime | Use comma-ok |
panic: runtime error: invalid memory address or nil pointer dereference | Runtime | Check nil, return untyped nil |
strconv.ParseInt: parsing "300": value out of range | strconv | Use the right bit size and check err |
Commands and flags Must-know
| Command | Purpose |
|---|---|
go vet ./... | Standard analyzers |
go vet -vettool=$(which shadow) ./... | Run the shadow analyzer |
go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow@latest | Install it |
go install golang.org/x/tools/cmd/stringer@latest | Install stringer |
go generate ./... | Run //go:generate lines |
staticcheck ./... | Run staticcheck |
go test -race ./... | Race detector for shared zero values |
GOARCH=386 go build ./... | Check 32-bit int assumptions |
Where each rule is applied Good to know
| Rule | Applied at |
|---|---|
| Constant representability | Compile time, type checker |
| Constant expression evaluation | Compile time, arbitrary precision |
| Zero initialisation | Allocation: stack frame zeroing or mallocgc |
| Integer wrap-around | CPU arithmetic, no check inserted |
| Type assertion | Run time, compares the interface's type word |
| Nil map write | Run time panic from the map implementation |
Solving the classic problems
Problem: an enum value is out of range after a deploy
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Zero value invalid | StatusUnknown at 0 | A forgotten field is caught | One extra constant |
Valid() at the boundary | Check after decode and before save | Rejects Status(77) | Call it everywhere |
| Marshal by name | MarshalText | Stable across reorderings | Renames break data |
Database CHECK | CHECK (status IN (...)) | The database enforces it | Migration per new value |
Problem: err != nil after a successful call
Return the literal nil from any function whose result type is an interface; never return a concrete nil pointer variable through error. See the Before/After below.
Problem: a silent overflow or truncation
| Solution | How | Advantage | Cost |
|---|---|---|---|
| Checked conversion helper | ToInt32 returning ErrOverflow | Explicit error | Boilerplate |
strconv.ParseInt(s, 10, 8) | Bit size argument | Library checks range | Text input only |
| Wider type | int64 for sums | Avoids the problem | Memory |
math/big | Arbitrary precision | Exact | Slower, verbose |
| Compare before adding | AddInt64 | No overflow | Extra branch |
Problem: a shadowed variable
Declare the variable first with var, assign with =, or move the code into a helper function that returns the value. Add shadow to CI.
Problem: unit mix-ups and swapped IDs
Use defined types (UserID, OrderID, Celsius, time.Duration) so the compiler rejects wrong arguments.
Go
Before
The bad design compiles: a typed nil through error and a shadowed variable, both exercised by tests so the wrong behaviour is documented.
func MayFailBuggy(fail bool) error {
var e *MyErr
if fail {
e = &MyErr{Code: 7}
}
return e // non-nil interface even when fail is false
}After
func MayFail(fail bool) error {
if fail {
return &MyErr{Code: 7}
}
return nil // untyped nil: the interface is empty
}The Go angle
Go's type system is deliberately small: no implicit numeric conversions, no enum keyword, no constructors. The standard library shows the idioms: time.Duration is a defined int64 with typed constants (time.Second), os.FileMode is a bit-flag type with a String(), http.StatusOK is an untyped integer constant, and sync.Mutex and bytes.Buffer are usable as zero values. Follow them: defined types for domain values, iota for small closed sets, stringer for names, and zero values that are safe.
Choosing
| Situation | Recommended | Extra technique | Reason |
|---|---|---|---|
| Fixed set of named states | Defined integer type plus iota, zero is Unknown | stringer, Valid() | Compact and safe |
| Set of options combined together | 1 << iota bit flags | Has/With/Without | One word, fast |
| Names must survive reordering | Enum as string type or MarshalText | CHECK constraint | Stable storage |
| Quantity with units | Defined type (Celsius, ByteSize) | Conversion methods | Compiler stops mixing |
| Need exact large numbers | Untyped const or math/big | n/a | Exact arithmetic |
| Money | Integer minor units or decimal type | Never float64 | Rounding |
| Rename a type across packages | Alias type A = B | Remove later | Gradual refactor |
| Reuse a name for a new purpose | Defined type type A B | Methods | New identity |
| Index or length | int | n/a | Standard library convention |
| Fixed-width wire or storage value | int32, int64, uint16 | Checked conversions | Same on every platform |
In architecture: from a single process to a distributed system
Monolith: one process, one database
Types, constants and enums live next to the code that uses them. An OrderStatus enum in one package is imported by handlers and repositories. The main discipline is the safe zero value and Valid() at the boundary where untrusted input enters (HTTP, queue, database).
Modular monolith and multiple databases
Each module owns its enum and exposes it only through its package API. Another module should not switch on orders.StatusPaid internal numbers; it should use methods such as IsFinal(). Persist enums by name so the schema in the database is independent of the Go declaration order, see Schema Design.
Microservices
An enum crosses a process boundary as a string or a number in JSON, Protocol Buffers or a message. The sender and receiver may be deployed at different times, so the receiver must tolerate values it does not know:
1 orders service v2 adds StatusRefunded = "refunded"
2 orders -> events topic: {"order_id": 7, "status": "refunded"}
3 billing service v1 (old) decodes -> ParseStatus returns ErrInvalidStatus
4 billing must decide: reject, park the message in a dead-letter queue, or treat as Unknown
5 Fix: add the value to consumers first (expand), then producers (contract)Protocol Buffers enums require number 0 as the default value, which is the same "zero is Unknown" rule. See Message Design & Schema Evolution and API Versioning.
Distributed data: replicas, caches and stored enums
A value cached in Redis or stored in a replica outlives the code that wrote it. Numeric enums in a cache are dangerous after a reorder; string names survive. A bigint ID stored as an int loses data on 32-bit builds. 64-bit integers in JSON are read by JavaScript as doubles and lose precision above 2^53, so identifiers are often exchanged as strings; see ID Generation at Scale.
Scaling path: 1x, 10x, 100x
| Load | Type and constant concern | Action |
|---|---|---|
| 1x | Correctness of types | Zero values, Valid(), vet in CI |
| 10x | Counters and sums approach int32/int64 limits; struct size affects memory | Use int64 explicitly, order fields, checked conversions |
| 100x | Millions of structs in memory; stored enums in many systems | Field ordering (unsafe.Sizeof), string enums with versioned schemas, uint64 ID ranges |
Lab
Everything below runs on the host with Go only; no containers. The code is in docs/snippets/go/values-variables-constants-enums/go.
$ cd docs/snippets/go/values-variables-constants-enums/go
$ go run ./cmd/tour
bool 1 bytes
int8 1 bytes
byte 1 bytes
rune 4 bytes
int 8 bytes
int64 8 bytes
uint 8 bytes
uintptr 8 bytes
float64 8 bytes
complex128 16 bytes
string 16 bytes
[]int 24 bytes
map[string]int 8 bytes
chan int 8 bytes
func() 8 bytes
any 16 bytes
Padded: 32 Packed: 16
default types: [int float64 int32 complex128 string bool]
0.1+0.2 constant: 0.3 runtime: 0.30000000000000004
KB, MB, GB: 1024 1.048576e+06 1.073741824e+09
PickBuggy: fallback PickFixed: db-1
int8(200): -56 uint(-1): 18446744073709551615 MaxInt64+1: -9223372036854775808
typed nil != nil: true | fixed: false
paid Status(42) read|delete(Real output, Go 1.27.4 on darwin/arm64.)
- Read the output above and predict each line before running: why is
string16 bytes, and why isMBprinted as1.048576e+06? (ByteSizeis afloat64, and%vof a largefloat64uses exponent form.) - Run
go test -race ./...in the module. All eight packages pass. - Run the shadow analyzer:
go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow@latestthengo vet -vettool=$(which shadow) ./shadowing. Real output:shadowing/shadowing.go:21:3: declaration of "name" shadows declaration at line 19and three more lines forScopes. - Put this in a scratch module and compile it to see the real errors:
package main
import "fmt"
func main() {
var a int8 = 200
var b uint = -1
const d = int32(1) << 33
x := 3
y := 2.5
fmt.Println(x + y)
}./bad1.go:17:15: cannot use 200 (untyped int constant) as int8 value in variable declaration (overflows)
./bad1.go:18:15: cannot use -1 (untyped int constant) as uint value in variable declaration (overflows)
./bad1.go:20:12: int32(1) << 33 (constant 8589934592 of type int32) overflows int32
./bad1.go:23:14: invalid operation: x + y (mismatched types int and float64)(Real compiler output, line numbers from a longer file.)
- Regenerate the stringer file:
go install golang.org/x/tools/cmd/stringer@latestthengo generate ./enum. The result matchesstatus_string.gobyte for byte. - Cross-compile for 32-bit to see
intchange meaning:GOARCH=386 go test ./sizes. Expected: the size tests are skipped on 32-bit; the rest pass (expected, not run). - Database step: apply the
CREATE TABLE ordersSQL above in PostgreSQL and insertstatus = 'lost'. Expected:ERROR: new row for relation "orders" violates check constraint "orders_status_check"(expected, not run).
Common misconceptions
| Belief | Reality |
|---|---|
const x = 5 is an int | It is an untyped constant; it becomes int, float64, Duration etc. when used |
| Integer overflow panics in Go | Variables wrap silently; only constants are checked at compile time |
int is always 32 bits | It is 32 or 64 depending on the platform |
len(s) counts characters | It counts bytes |
| Go has enums | It has typed constants and iota; any value of the type is legal |
iota is global | It resets per const block and counts specs |
| A nil interface and an interface holding a nil pointer are equal | The latter is non-nil because its type is set |
x.(T) converts a value | It only unwraps; on mismatch it panics unless you use comma-ok |
:= always creates a variable in the current scope | It reuses variables declared in the same scope and shadows outer ones |
| An alias is a new type | It is the identical type with another name |
0.1 + 0.2 == 0.3 is false in Go | For constants it is true (exact arithmetic); for float64 variables it is false |
| Reading a nil map panics | Only writing does |
Cheat sheet
| Topic | What to remember |
|---|---|
| Types | int for counts, fixed-width for contracts, float64 for fractions, never floats for money |
| Strings | Immutable bytes; len is bytes; []byte(s) copies |
| Constants | Exact and untyped until used; typed constants must fit |
| Default types | int, float64, int32 (rune), complex128, string, bool |
:= | Needs a new name; shadows in inner blocks |
| Zero value | Design types so it works; make 0 the "unset" enum value |
nil | Six nilable kinds; return literal nil through interfaces |
| Conversion | Explicit, unchecked for variables, checked for constants |
| Assertion | Use v, ok := x.(T) unless a failure is a bug |
iota | Per block, per spec; _ skips; 1 << iota for flags |
| Enums | Zero is Unknown, stringer, Valid(), exhaustive switch with error default |
| Marshalling | MarshalText, Valuer, Scanner; persist names not numbers |
| Alias vs defined | = means same type; no = means new type |
| Tools | go vet, shadow, staticcheck, exhaustive in CI |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — What type does x := 'a' have, and what is its value? Must-know
Answer
Answer: rune, which is int32; its value is 97.
2 — Why does const Four int8 = Huge >> 98 compile when Huge = 1 << 100? Good to know
Answer
Answer: Constant expressions are exact and untyped; only the final value 4 must fit int8.
3 — What does var b uint8 = 255; b++ do? Must-know
Answer
Answer: It wraps to 0 at run time. There is no panic and no error.
4 — Why is err != nil true when mayFail returns a nil *MyErr? Must-know
Answer
Answer: The interface holds type *MyErr and a nil value; an interface is nil only when both type and value are unset.
5 — What is the difference between float64(x) and x.(float64)? Must-know
Answer
Answer: The first converts a numeric value; the second unwraps an interface and panics if the dynamic type is not float64.
6 — What values does const (A = iota * 10; B; C) produce? Important
Answer
Answer: 0, 10 and 20; the omitted expression repeats.
7 — Why should an enum's zero value be Unknown? Important
Answer
Answer: A forgotten or default-initialised field must not look like a valid business state.
8 — How do you clear a flag bit? Important
Answer
Answer: p &^ flag (AND NOT).
9 — When are type A B and type A = B interchangeable? Important
Answer
Answer: Only for the alias: it is identical to B. A defined type needs a conversion.
10 — Which tool reports shadowed variables, and is it part of the default go vet? Good to know
Answer
Answer: The shadow analyzer, run with go vet -vettool; it is not in the default set.
11 — What is unsafe.Sizeof("hello") on 64-bit? Good to know
Answer
Answer: 16 bytes: the string header (pointer and length), not the text.
Glossary
| Term | Meaning |
|---|---|
int, uint | Platform-sized signed and unsigned integers |
int64 | Signed 64-bit integer |
uintptr | Unsigned integer large enough to hold a pointer's bits |
float64 | IEEE 754 double |
complex128 | Complex number of two float64 |
byte | Alias for uint8 |
rune | Alias for int32, one Unicode code point |
string | Immutable sequence of bytes |
| immutability | A string's bytes cannot be changed after creation |
bool | true or false |
| literal | A value written in source such as 42 or "go" |
| untyped constant | Constant with no type until used; exact arithmetic |
| typed constant | Constant with a fixed type that must hold the value |
| constant expression | Expression of constants evaluated at compile time |
| default type | The type an untyped constant takes in := |
| overflow | A value outside the range of its type |
var | Variable declaration |
:= | Short variable declaration, function bodies only |
const | Constant declaration |
| shadowing | An inner declaration hiding an outer one |
| zero value | The value of a variable declared without an initialiser |
nil | Zero value of pointers, slices, maps, channels, functions, interfaces |
| untyped nil | The predeclared nil identifier |
| typed nil | A nil pointer or similar of a concrete type, non-nil inside an interface |
| conversion | T(x), explicit change of type |
| type assertion | x.(T), run-time check of an interface's dynamic type |
iota | Per-block constant counter |
| enum | Convention: named type plus constants, no keyword |
| bit flag | One bit of an integer used as an option |
stringer | Tool generating String() for constant types |
| exhaustive switch | A switch that names every constant of the type |
| named type | A defined type type A B with its own identity |
| type alias | type A = B, another name for the same type |
| scope | Region where a name is visible |
| block | A { } region, also implicit blocks of statements |
| multiple assignment | Tuple assignment where all operands are evaluated first |
| truncation | Dropping the fraction or high bits in a conversion |
math.MaxInt64 | Largest int64, 9223372036854775807 |
unsafe.Sizeof | Size in bytes of a value, including padding |
go vet | Standard static analyser shipped with Go |
staticcheck | Third-party linter with SA, S, ST and QF checks |
For PHP/Laravel developers
PHP converts types implicitly and has no static numeric types in userland arithmetic; Go refuses to. The PHP enum (since 8.1) validates values, Go's does not.
<?php
// PHP 8.1+: a backed enum validates on construction
enum Status: string {
case Pending = 'pending';
case Paid = 'paid';
}
Status::from('lost'); // throws ValueError
Status::tryFrom('lost'); // null| PHP / Laravel | Go |
|---|---|
"5" + 3 is 8 | "5" + 3 does not compile; strconv.Atoi |
enum Status: string with from() | type Status uint8 plus ParseStatus |
Eloquent casts to an enum | driver.Valuer and sql.Scanner |
null for "no value" | zero value, nil, or sql.Null[T] |
Integer overflow becomes float | Integer overflow wraps |
define(), class constants | const and iota |
(int) $x truncates | int(x), also unchecked |
| Variables are function-scoped | Variables are block-scoped; := can shadow |
References
All URLs returned HTTP 200 when fetched on 2026-11-26. pkg.go.dev returns 403 to non-browser clients; package documentation was read with go doc from the installed toolchain.
- The Go Programming Language Specification: constants, constant expressions, iota, conversions, zero value, alias declarations, blocks
- Effective Go: constants (
iota,ByteSize), allocation and zero values - Go FAQ: "Why is my nil error value not equal to nil?"
- Go blog: Constants
- Go blog: Strings, bytes, runes and characters
- Go Code Review Comments
- Go 1.12 release notes:
-shadowremoved from vet - Go 1.22 release notes: loop variables, range over integers
- Go 1.24 release notes: generic type aliases,
omitzero - stringer source and documentation
- shadow analyzer source
- Staticcheck checks: SA4003, SA4006, SA4022, SA4023, SA9004, ST1012