Skip to content

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 forGo to
Tables you can memorise in one minuteEverything in one minute
Why Go has untyped constants and zero valuesWhy it exists
Spec, Effective Go, the constants blog postWhere it comes from
int versus int64, uint, float64, complex128, byte, rune, boolBasic types and sizes
Why s[0] = 'J' does not compileStrings and immutability
1 << 100, 0.1 + 0.2, default typesUntyped constants
const, typed constant, constant expressionTyped constants and overflow
var, :=, package-level declarationsvar versus :=
The name that never changesShadowing
0, "", nil, usable sync.Mutex and bytes.BufferZero values
err != nil is true but the function succeedednil and typed nil
float64(i) versus x.(string)Conversions versus type assertions
uint(-1), int8(200), math.MaxInt64 + 1Numeric conversion traps
iota, skip zero, Weekday, ByteSizeiota
Status enums with String() and stringerEnums
1 << iota, &^, permissionsBit flags
JSON and database/sql for enumsEnum marshalling
type A B versus type A = BNamed types and aliases
Blocks, if x := ..., loop variablesScope and blocks
a, b = b, a, evaluation orderMultiple assignment
math.MaxInt64, unsafe.Sizeof, paddingmath constants and unsafe.Sizeof
go vet, shadow, staticcheck findingsVet and staticcheck
Exact messagesMechanics
Fixes for classic bugsSolving the classic problems
Before/after codeGo
Which construct for which jobChoosing
Monolith to distributed systemIn architecture
Runnable experimentsLab
Wrong beliefs, cheat sheet, termsMisconceptions, Cheat sheet, Glossary

Everything in one minute ​

The ideas. Each row is unpacked in the concept catalogue.

IdeaIn plain wordsTiny exampleWhat goes wrong
Static typeEvery variable has one type fixed at compile timevar n int64Mixing int and int64 is a compile error
Zero valueA declared variable is never uninitialisedvar s string is ""A zero value that looks valid but means "not set"
Untyped constantA literal or const with no type until usedconst Big = 1 << 100Assigning it to a too-small type is rejected
Default typeThe type a constant gets in :=x := 3.14 is float64x := 5 / 2 is 2, not 2.5
iotaA counter inside one const blockA = iota is 0, B is 1A reordered block silently renumbers stored values
Shadowing:= in an inner block declares a new variableif x, err := f(); ...The outer variable never changes
Typed nilAn interface holding a nil pointer is not nilvar e *MyErr; return eerr != nil is true on success
ConversionExplicit change of type: T(x)float64(i)Truncation and wrap-around without an error

The numeric types.

TypeSizeRange or meaningUse it for
int, uint32 or 64 bits (platform)math.MaxInt64 on 64-bitIndexes, lengths, counts
int8 int16 int32 int641, 2, 4, 8 bytesTwo's complementWire formats, database columns, exact width
uint8 (byte) uint16 uint32 uint641, 2, 4, 8 bytes0 up to 2^n - 1Bytes, bit sets, hashes
uintptrPointer-sized unsigned integerAn address as a number, not a referenceunsafe code only
float32, float644, 8 bytesIEEE 754 binary floating pointfloat64 for almost everything
complex64, complex1288, 16 bytesReal plus imaginary partSignal processing; rare in services
rune (int32)4 bytesOne Unicode code pointIterating text by character
bool1 bytetrue, falseFlags and conditions
string16 bytes headerImmutable bytes, usually UTF-8Text

The errors you will meet.

MessageMeaningFirst move
cannot use 200 (untyped int constant) as int8 value in variable declaration (overflows)A constant does not fit the typePick a wider type or fix the value
invalid operation: x + y (mismatched types int and float64)No implicit numeric conversionConvert one operand explicitly
declared and not used: errA local is never readUse it or assign to _
result parameter err not in scope at returnA bare return after shadowing a named resultUse = not :=, or return values explicitly
assignment to entry in nil mapWriting into a nil map panicsmake the map first
interface conversion: interface {} is string, not intA single-value type assertion failedUse the v, ok := x.(T) form
conversion from int to string yields a string of one rune, not a string of digitsgo vet stringintconvstrconv.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.

ChoiceBenefitCost
No implicit numeric conversionint and int64 never mix silently, so wrap-around is visible in the sourceYou write float64(n) and int64(n) often
Zero value for every typeNo uninitialised memory; many types need no constructorThe zero value can look valid when it means "unset"
Untyped exact constantstime.Second * 2 and 1 << 40 just workA constant behaves differently from a variable of the same value
iota instead of an enum keywordOne small mechanism covers sequences, bit flags and unitsNo built-in validity check, no automatic String()
Lexical block scope with :=Short code, no declaration ceremonyAccidental 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 ​

  1. "A const is just a variable that cannot change." No: an untyped constant has no type and unlimited precision until it is used, so const x = 5 can be an int, a float64 or a time.Duration depending on the use.
  2. "Go has enums." It does not; it has typed constants and iota. Nothing stops Status(42) from existing.
  3. "nil is 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.

FeatureSinceSource
Alias declarations type A = BGo 1.9Spec, "Alias declarations"
go vet without the -shadow flag; shadow as a separate toolGo 1.12Go 1.12 release notes
for loop variable per iteration, for i := range 10Go 1.22Go 1.22 release notes
Generic type aliasesGo 1.24Go 1.24 release notes
omitzero in encoding/json struct tagsGo 1.24Go 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.

text
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++                 // -9223372036854775808

Real 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.

TypePostgreSQL columnMySQL columnWire (Protocol Buffers)
int32integerINTint32
int64bigintBIGINTint64
uint8smallint (no unsigned type)TINYINT UNSIGNEDuint32 (no 8-bit type)
float64double precisionDOUBLEdouble
boolbooleanTINYINT(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.

go
// 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
}
Field order changes the size (18 px per byte, 64-bit platform)PaddedPackedApad 7B int64Cpad 3D int32Epad 7B int64D int32ACEpA bool, B int64, C bool, D int32, E bool: 32 bytes, 17 of them paddingB int64, D int32, A, C, E bool: 16 bytes, 1 of them padding (p)unsafe.Sizeof(Padded{}) = 32 unsafe.Sizeof(Packed{}) = 16

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.

text
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.

text
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 float64

Real 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.

LiteralKindDefault type in :=
42, 0x2A, 0b101010, 0o52, 1_000_000integerint
3.14, 1e9, 0x1p-2floating-pointfloat64
'x', '世'runerune (int32)
1i, 2.5 + 3icomplexcomplex128
"go", `raw`stringstring
true, falsebooleanbool
Operation on untyped operandsResult kind
integer op integerinteger (division truncates)
integer op floating-pointfloating-point
rune op integerrune
any op complexcomplex
comparisonuntyped boolean
shift with untyped left operandinteger constant
go
// 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
}
Compile time: exact, untypedTyped: fixed size, wraps at run time1 << 100 0.1 + 0.2 'x'3 / 2 = 1 3 / 2.0 = 1.5kinds: integer, rune,floating-point, complex(result takes the later kind)int int64 uint8 float64complex128 string boolx := 42 gives inty := 2.5 gives float64r := 'x' gives int32 (rune)var b uint8 = 300 rejected: overflows uint8var f float64 = 1 << 100 ok: exact value fitsuint(-1) rejected: -1 cannot be representedx := 255; uint8(x + 1) no error: wraps to 0 at run timeassignment,:= or typedoperand

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.

text
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 0

Real 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.

CaseWhen it is checkedResult
Constant too big for the declared typeCompile timeBuild error (overflows)
Typed constant arithmetic out of rangeCompile timeconstant ... overflows int32
Variable arithmetic out of rangeRun timeWraps silently
Float constant converted to integer with a fractionCompile timecannot convert 3.14 (untyped float constant) to type int
Float variable converted to integer out of rangeRun timeImplementation-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 :=.

text
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-time

Real 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.

FormWhereTypeZero value?
var x TAnywhereTYes
var x = eAnywhereDefault type of eNo, set by e
x := eFunction bodies onlyDefault type of eNo
const x = eAnywhereUntyped or typedNot a variable
x, y = y, xFunction bodiesExisting variablesn/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).

text
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.

CauseSymptomFix
x, err := f() inside a block while x is outerOuter x unchangedDeclare var err error and use x, err = f()
if v, ok := m[k]; ok {}Fine: scoped on purposeKeep it, v and ok are only needed inside
Named result shadowed, bare returnCompile errorAssign with =
Loop for _, x := range xs inside a function with xOuter x hiddenRename one
go
// 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.

text
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 map

Real 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.

TypeZero valueSafe to use?
int, float640Yes
string""Yes
boolfalseYes
pointernilReading through it panics
slicenil (len 0, cap 0)Yes: append, range, len
mapnilRead yes, write panics
channelnilSend and receive block forever
funcnilCalling it panics
interfacenil (no type, no value)Calling a method panics
struct, arrayEvery field or element zeroedDepends on the fields
go
// 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.

text
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 succeeded

Real 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.

Kindx == nil allowedBehaviour when nil
pointeryesDereference panics: invalid memory address or nil pointer dereference
sliceyeslen 0, append works
mapyesRead gives zero value, write panics
channelyesSend and receive block forever; close panics
funcyesCall panics
interfaceyesMethod call panics; nil only if type and value are unset
struct, int, stringnoNot nilable
go
// 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})
}
An interface value is two words: (type, value)var err errortypevaluenilunseterr == nil is truereturn (*MyErr)(nil)typevalue*MyErrnilerr == nil is falsereturn &MyErr{...}typevalue*MyErr0xc000...err == nil is falseFix: return the literal nil from the function that returns errorif bad { return &MyErr{} } return nilstaticcheck SA4023 flags comparisons that can never be true

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.

text
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 uint8

Real 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.

OperationCheckedFailure
T(x) with constant xCompile timeBuild error
T(x) numeric, variable xNeverTruncation or wrap-around
string(rune), []byte(s)Compile timeCopy, no error
x.(T)Run timePanic
v, ok := x.(T)Run timeok == false
switch x.(type)Run timeFalls 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.

text
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++   // -9223372036854775808

Real 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.

TrapExampleSafe version
Truncationint(f)int(math.Round(f)) after a range check
Narrowingint32(x)Check x >= math.MinInt32 && x <= math.MaxInt32
Signed to unsigneduint(i) with i < 0Reject negatives first
Overflowa + b on int64Compare against the limit before adding
Text from numberstring(65)strconv.Itoa(65) or string(rune(65)); vet flags it
go
// 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.

text
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.

PatternCodeValues
Plain sequenceA = iota then B, C0, 1, 2
Skip zero_ = iota then AA is 1
Start at 1A = iota + 11, 2, 3
Powers of twoA = 1 << iota1, 2, 4, 8
UnitsKB = 1 << (10 * iota)1024, 1048576
Skip a value_ between namesGap in the numbering
Two names per lineA, B = iota, iota * 10Same 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.

text
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.

DecisionRecommendedWhy
Underlying typeuint8 or intSmall, comparable, cheap to store
Value 0An explicit Unknown/InvalidThe zero value is the "unset" value
NumberingNever renumber stored valuesReordering the block changes persisted meaning
String()stringer -linecommentNo hand-written table to drift
SwitchesList every constant, default returns an errorA new constant fails loudly
Linterexhaustive (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.

go
// 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
}
go
// 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]]
}
Sequential: Status = iotaBit flags: Perm = 1 << iotaiotaconstantString()0StatusUnknownunknown1StatusPendingpending2StatusPaidpaid3StatusShippedshipped4StatusCancelledcancelled5statusEndrange guardPermReadPermWritePermDelete0 0 10 1 01 0 0= 1= 2= 4p = PermRead | PermWrite gives 0 1 1p & PermWrite == PermWrite gives truep &^ PermRead gives 0 1 0Perm(8) is outside PermAllThe zero value of each type is the invalid or empty one on purpose

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).

text
1  p := PermRead | PermWrite       // 0b011
2  p & PermWrite == PermWrite      // true
3  p &^ PermRead                   // 0b010
4  Perm(8).Valid()                 // false: bit outside PermAll

Real scenario: file permission bits, feature flags in a token, role sets in a JWT, os.O_RDWR|os.O_CREATE open flags.

OperatorMeaningUse
|ORSet bits
&ANDTest bits
&^AND NOTClear bits
^XOR or NOTToggle bits
<< >>ShiftBuild constants
go
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.

text
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 status

Real 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.

LayerInterfaceStored as
JSON, XMLencoding.TextMarshaler / TextUnmarshalerName string
database/sql writedriver.Valuertext column or a Postgres enum
database/sql readsql.ScannerSame
Protocol BuffersGenerated enum, number 0 must be the defaultNumber
Logsfmt.StringerName
sql
-- 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.

text
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 alias

Real 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.

AspectDefined type type A BAlias type A = B
IdentityNew, distinct from BIdentical to B
MethodsOwn method set, none inherited from BMethods of B
Assignable from BOnly with conversion (or untyped constant)Yes
%T printspkg.Apkg.B
UseDomain types, units, enumsRefactoring, renames, short names
go
// 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.

text
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, 3

Real 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.

BlockScope of a name declared in it
UniverseWhole program (int, nil, true, len)
PackageAll files of the package
FileThe file (import names)
FunctionParameters and results to the end of the function
if/for/switch headerThat statement and its branches
Explicit { }Up to the closing brace
case clauseThat 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.

text
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 i

Real 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.

FormMeaning
a, b = b, aSwap
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 = <-chComma-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.

text
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.

ConstantValueType of use
math.MaxInt8, MinInt8127, -128Range checks
math.MaxInt322147483647PostgreSQL integer ceiling
math.MaxInt649223372036854775807bigint ceiling
math.MaxUint324294967295IPv4 as a number
math.MaxIntMaxInt32 or MaxInt64Platform limit
math.Pi, math.EUntyped floatsGeometry
math.MaxFloat64about 1.8e308Largest 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).

text
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).

CheckToolFinds
stringintconvgo vetstring(i) for an integer i
shadowshadow vettoolInner := hiding an outer variable
SA4003staticcheckComparing unsigned with a negative constant
SA4022, SA4023staticcheck&x == nil, impossible interface-to-nil comparison
SA4006staticcheckValue assigned and never read
SA9004staticcheckOnly the first constant of a group has an explicit type
ST1012staticcheckError variable not named errFoo
exhaustivegolangci-lintSwitch 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.

MessageWhere it comes fromFix
cannot use 200 (untyped int constant) as int8 value in variable declaration (overflows)CompilerUse a wider type
cannot use -1 (untyped int constant) as uint value in variable declaration (overflows)CompilerReject negatives earlier
cannot use big (untyped int constant 1267650600228229401496703205376) as int value in variable declaration (overflows)CompilerUse math/big or float64
int32(1) << 33 (constant 8589934592 of type int32) overflows int32CompilerWiden the type before shifting
invalid operation: x + y (mismatched types int and float64)CompilerConvert one operand
declared and not used: errCompilerUse or _
result parameter err not in scope at returnCompilerAvoid shadowing named results
conversion from int to string yields a string of one rune, not a string of digitsgo vetstrconv.Itoa
declaration of "name" shadows declaration at line 19shadow toolUse =
panic: assignment to entry in nil mapRuntimemake the map
panic: interface conversion: interface {} is string, not intRuntimeUse comma-ok
panic: runtime error: invalid memory address or nil pointer dereferenceRuntimeCheck nil, return untyped nil
strconv.ParseInt: parsing "300": value out of rangestrconvUse the right bit size and check err

Commands and flags Must-know ​

CommandPurpose
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@latestInstall it
go install golang.org/x/tools/cmd/stringer@latestInstall 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 ​

RuleApplied at
Constant representabilityCompile time, type checker
Constant expression evaluationCompile time, arbitrary precision
Zero initialisationAllocation: stack frame zeroing or mallocgc
Integer wrap-aroundCPU arithmetic, no check inserted
Type assertionRun time, compares the interface's type word
Nil map writeRun time panic from the map implementation

Solving the classic problems ​

Problem: an enum value is out of range after a deploy ​

SolutionHowAdvantageCost
Zero value invalidStatusUnknown at 0A forgotten field is caughtOne extra constant
Valid() at the boundaryCheck after decode and before saveRejects Status(77)Call it everywhere
Marshal by nameMarshalTextStable across reorderingsRenames break data
Database CHECKCHECK (status IN (...))The database enforces itMigration 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 ​

SolutionHowAdvantageCost
Checked conversion helperToInt32 returning ErrOverflowExplicit errorBoilerplate
strconv.ParseInt(s, 10, 8)Bit size argumentLibrary checks rangeText input only
Wider typeint64 for sumsAvoids the problemMemory
math/bigArbitrary precisionExactSlower, verbose
Compare before addingAddInt64No overflowExtra 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.

go
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 ​

go
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 ​

SituationRecommendedExtra techniqueReason
Fixed set of named statesDefined integer type plus iota, zero is Unknownstringer, Valid()Compact and safe
Set of options combined together1 << iota bit flagsHas/With/WithoutOne word, fast
Names must survive reorderingEnum as string type or MarshalTextCHECK constraintStable storage
Quantity with unitsDefined type (Celsius, ByteSize)Conversion methodsCompiler stops mixing
Need exact large numbersUntyped const or math/bign/aExact arithmetic
MoneyInteger minor units or decimal typeNever float64Rounding
Rename a type across packagesAlias type A = BRemove laterGradual refactor
Reuse a name for a new purposeDefined type type A BMethodsNew identity
Index or lengthintn/aStandard library convention
Fixed-width wire or storage valueint32, int64, uint16Checked conversionsSame 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:

text
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 ​

LoadType and constant concernAction
1xCorrectness of typesZero values, Valid(), vet in CI
10xCounters and sums approach int32/int64 limits; struct size affects memoryUse int64 explicitly, order fields, checked conversions
100xMillions of structs in memory; stored enums in many systemsField 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.

text
$ 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.)

  1. Read the output above and predict each line before running: why is string 16 bytes, and why is MB printed as 1.048576e+06? (ByteSize is a float64, and %v of a large float64 uses exponent form.)
  2. Run go test -race ./... in the module. All eight packages pass.
  3. Run the shadow analyzer: go install golang.org/x/tools/go/analysis/passes/shadow/cmd/shadow@latest then go vet -vettool=$(which shadow) ./shadowing. Real output: shadowing/shadowing.go:21:3: declaration of "name" shadows declaration at line 19 and three more lines for Scopes.
  4. Put this in a scratch module and compile it to see the real errors:
go
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)
}
text
./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.)

  1. Regenerate the stringer file: go install golang.org/x/tools/cmd/stringer@latest then go generate ./enum. The result matches status_string.go byte for byte.
  2. Cross-compile for 32-bit to see int change meaning: GOARCH=386 go test ./sizes. Expected: the size tests are skipped on 32-bit; the rest pass (expected, not run).
  3. Database step: apply the CREATE TABLE orders SQL above in PostgreSQL and insert status = 'lost'. Expected: ERROR: new row for relation "orders" violates check constraint "orders_status_check" (expected, not run).

Common misconceptions ​

BeliefReality
const x = 5 is an intIt is an untyped constant; it becomes int, float64, Duration etc. when used
Integer overflow panics in GoVariables wrap silently; only constants are checked at compile time
int is always 32 bitsIt is 32 or 64 depending on the platform
len(s) counts charactersIt counts bytes
Go has enumsIt has typed constants and iota; any value of the type is legal
iota is globalIt resets per const block and counts specs
A nil interface and an interface holding a nil pointer are equalThe latter is non-nil because its type is set
x.(T) converts a valueIt only unwraps; on mismatch it panics unless you use comma-ok
:= always creates a variable in the current scopeIt reuses variables declared in the same scope and shadows outer ones
An alias is a new typeIt is the identical type with another name
0.1 + 0.2 == 0.3 is false in GoFor constants it is true (exact arithmetic); for float64 variables it is false
Reading a nil map panicsOnly writing does

Cheat sheet ​

TopicWhat to remember
Typesint for counts, fixed-width for contracts, float64 for fractions, never floats for money
StringsImmutable bytes; len is bytes; []byte(s) copies
ConstantsExact and untyped until used; typed constants must fit
Default typesint, float64, int32 (rune), complex128, string, bool
:=Needs a new name; shadows in inner blocks
Zero valueDesign types so it works; make 0 the "unset" enum value
nilSix nilable kinds; return literal nil through interfaces
ConversionExplicit, unchecked for variables, checked for constants
AssertionUse v, ok := x.(T) unless a failure is a bug
iotaPer block, per spec; _ skips; 1 << iota for flags
EnumsZero is Unknown, stringer, Valid(), exhaustive switch with error default
MarshallingMarshalText, Valuer, Scanner; persist names not numbers
Alias vs defined= means same type; no = means new type
Toolsgo vet, shadow, staticcheck, exhaustive in CI

Self-check: questions & answers ​

Show:
  • 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 ​

TermMeaning
int, uintPlatform-sized signed and unsigned integers
int64Signed 64-bit integer
uintptrUnsigned integer large enough to hold a pointer's bits
float64IEEE 754 double
complex128Complex number of two float64
byteAlias for uint8
runeAlias for int32, one Unicode code point
stringImmutable sequence of bytes
immutabilityA string's bytes cannot be changed after creation
booltrue or false
literalA value written in source such as 42 or "go"
untyped constantConstant with no type until used; exact arithmetic
typed constantConstant with a fixed type that must hold the value
constant expressionExpression of constants evaluated at compile time
default typeThe type an untyped constant takes in :=
overflowA value outside the range of its type
varVariable declaration
:=Short variable declaration, function bodies only
constConstant declaration
shadowingAn inner declaration hiding an outer one
zero valueThe value of a variable declared without an initialiser
nilZero value of pointers, slices, maps, channels, functions, interfaces
untyped nilThe predeclared nil identifier
typed nilA nil pointer or similar of a concrete type, non-nil inside an interface
conversionT(x), explicit change of type
type assertionx.(T), run-time check of an interface's dynamic type
iotaPer-block constant counter
enumConvention: named type plus constants, no keyword
bit flagOne bit of an integer used as an option
stringerTool generating String() for constant types
exhaustive switchA switch that names every constant of the type
named typeA defined type type A B with its own identity
type aliastype A = B, another name for the same type
scopeRegion where a name is visible
blockA { } region, also implicit blocks of statements
multiple assignmentTuple assignment where all operands are evaluated first
truncationDropping the fraction or high bits in a conversion
math.MaxInt64Largest int64, 9223372036854775807
unsafe.SizeofSize in bytes of a value, including padding
go vetStandard static analyser shipped with Go
staticcheckThird-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
// 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 / LaravelGo
"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 enumdriver.Valuer and sql.Scanner
null for "no value"zero value, nil, or sql.Null[T]
Integer overflow becomes floatInteger overflow wraps
define(), class constantsconst and iota
(int) $x truncatesint(x), also unchecked
Variables are function-scopedVariables 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.

Built by Morteza Negahi