Built-in and composite types, zero values, implicit interfaces, type assertions, the nil-interface trap, and the basics of generics.
The problem
Go has a small, static type system, and most bugs come from not knowing what a value is before you touch it: its zero value, whether it can be compared, whether an interface is really nil. Interfaces and generics are the two tools for writing code that works over many types without losing static checking.
How it works
- Every type has a zero value (`0`, `""`, `false`, `nil`, or all fields zeroed), so `var x T` is always initialised. Good designs make the zero value useful.
- Composite types: arrays `[N]T` are values (length is part of the type); slices `[]T` are (pointer, len, cap) views of an array; maps are hash tables that need `make` before writes; structs group fields.
- A defined type (`type Celsius float64`) has the same underlying type but a different identity and its own method set; a type alias (`type A = B`) is just another name.
- Interfaces are satisfied implicitly: any type with the right methods implements them, with no `implements` keyword. Define interfaces where they are consumed, and keep them small.
- `any` is an alias for `interface{}`. Get the concrete value back with `v, ok := x.(T)` (never panics) or a `switch x := v.(type)`; the single-result form `x.(T)` panics on mismatch.
- An interface value is (dynamic type, dynamic value) and is `nil` only if both are absent. Returning a nil `*MyErr` as `error` yields a non-nil interface, so `err != nil` is true.
- Generics (Go 1.18+): `func Sum[T Number](xs []T) T`. A constraint is an interface that may list types (`~int | ~float64`); `~T` includes every type whose underlying type is T.
- `comparable` allows `==` and map keys; since Go 1.20 it is satisfied by interface types too, which can still panic at run time if the dynamic type is not comparable. `cmp.Ordered` covers `<`.
- Type arguments are usually inferred from function arguments; methods cannot declare their own type parameters, only the generic type can.
Go sketch
import "fmt"
type Shape interface {
Area() float64
}
type Rect struct{ W, H float64 }
func (r Rect) Area() float64 { return r.W * r.H }
type Number interface {
~int | ~int64 | ~float64
}
func Sum[T Number](xs []T) T {
var total T
for _, x := range xs {
total += x
}
return total
}
type MyErr struct{}
func (*MyErr) Error() string { return "my error" }
func mayFail(fail bool) error {
var p *MyErr
if fail {
p = &MyErr{}
}
// BUG: "return p" would return a non-nil error holding a nil *MyErr.
if p == nil {
return nil
}
return p
}
func describe(v any) string {
switch x := v.(type) {
case nil:
return "nil"
case int:
return fmt.Sprintf("int %d", x)
case Shape:
return fmt.Sprintf("shape %.1f", x.Area())
default:
return fmt.Sprintf("other %T", x)
}
}
func asRect(s Shape) (Rect, bool) {
r, ok := s.(Rect)
return r, ok
}Zero values you can use directly, and the nil-map write trap.
import "fmt"
type Stats struct {
Count int
Tags []string
Seen map[string]bool
}
func (s *Stats) Add(tag string) {
s.Count++
// append works on a nil slice.
s.Tags = append(s.Tags, tag)
// A nil map must be made before writing, otherwise: panic.
if s.Seen == nil {
s.Seen = make(map[string]bool)
}
s.Seen[tag] = true
}
func zero() {
var s Stats
s.Add("a")
fmt.Println(s.Count, len(s.Tags), s.Seen["a"])
var arr [3]int
b := arr
b[0] = 9
fmt.Println(arr, b)
}In practice
- io.Reader / io.Writer — One-method interfaces that make files, sockets, buffers and gzip streams interchangeable; the textbook case of small, consumer-side interfaces.
- sort / slices / maps — `slices.Sort`, `slices.Index` and `maps.Keys`-style helpers (Go 1.21+) replaced many hand-written loops with constrained generics.
- database/sql — `driver.Valuer` and `sql.Scanner` are implemented implicitly by user types such as nullable wrappers; no registration needed.
- Pitfall — Returning a typed nil pointer as an `error` or interface makes `x != nil` true; return the literal `nil` instead.
Trade-offs
Pros
- Implicit interfaces decouple packages: the consumer defines what it needs, producers need no import.
- Zero values and a tiny type system keep code predictable and easy to read.
- Generics remove copy-paste for containers and algorithms while staying statically checked.
Cons
- Typed-nil in an interface is not `nil`; this bites most often with `error`.
- `x.(T)` without the comma-ok form panics on mismatch; `comparable` types can still panic when comparing interfaces holding slices or maps.
- Writing to a nil map panics, and a slice shares its backing array with its sub-slices, so `append` can silently overwrite data.
- Generics are limited: no methods with type parameters, and overusing them where an interface suffices hurts readability.