Interfaces & generics
19 steps in 7 sets of Go.
Structs and methods, then interfaces, which Go satisfies implicitly. There is no implements keyword: if the methods match, the type qualifies, and that shapes how Go APIs are designed.
Then dynamic types and type switches, the standard interfaces worth knowing, generics as they finally arrived in 1.18, and a set on API shapes. Nineteen steps.
Structs & methods
- Structs and methodsComposite types, embedding, and receivers.
- Struct with methodA struct with a method, and the value-versus-pointer receiver choice.
- Struct embeddingEmbedding promotes the inner type's fields and methods to the outer one.
Interfaces
- InterfacesImplicit satisfaction: no
implementskeyword. - Interfaces are satisfied implicitlyNo implements keyword: a type has the methods, so it fits.
- Embedding interfacesA bigger interface is built from smaller ones, which is how io does it.
- The nil interface trapAn interface holding a nil pointer is not itself nil.
Dynamic types
- Type switchesOne switch over the dynamic type inside an interface value.
- Type assertionsPulling a concrete type back out, safely or with a panic.
Standard interfaces
- io.Reader and io.WriterThe two interfaces that let unrelated things be plumbed together.
- StringerA String method changes how fmt prints your type.
- sort.Interface and slices.SortFuncThe old three-method way, and the generic one that replaced it.
Generics
- GenericsType parameters and constraint interfaces.
- Type parameters and constraintsA constraint says what the type must support, and any is the loosest.
- Generic typesA struct can take a type parameter, and its methods reuse it.
- Generic map, filter and reduceWhat the standard library leaves to you, in ten lines.
API shapes
- Functional optionsThe Go answer to optional arguments: variadic functions that mutate a config.
- Range over functionGo 1.23 lets a function be ranged over, which is how iterators work now.
Encore
- wordcount.goA complete word-frequency program: read stdin, tally, sort, print.