All Go snippets · 36
Every snippet has its own focus page with an explanation and the output it produces.
Variables & Types · 4
- Short Variable DeclarationThe := operator declares and initialises in one step, inferring the type from the value. It only works inside a function.
- Zero ValuesGo never leaves a variable uninitialised. Numbers start at 0, strings empty, booleans false, and slices, maps and pointers nil.
- Constants And Iotaiota counts up from zero within a const block, giving you sequential values without writing each number by hand.
- No Implicit ConversionGo refuses to mix numeric types silently. Every conversion must be written out, which prevents accidental precision loss.
Control Flow · 4
- If With InitialiserAn if can declare a variable before its condition. That variable is scoped to the if and its else, keeping it out of the surrounding function.
- The Only LoopGo has exactly one loop keyword. Drop the init and post clauses and for behaves like a while loop.
- Switch Without BreakGo cases do not fall through, so no break is needed. A switch with no expression acts as a chain of if-else conditions.
- Range Over Slicerange yields the index and a copy of the element. Use _ for the index when you only care about values.
Functions · 5
- Multiple Return ValuesFunctions can return several values at once, which is why Go does not need output parameters or wrapper structs for simple cases.
- Named Return ValuesNamed results are pre-declared and a bare return sends them back. Useful in short functions, but harder to follow in long ones.
- Variadic FunctionsA ...T parameter collects any number of arguments into a slice. Inside the function it is an ordinary slice, empty when nothing is passed.
- Closures Capture StateThe returned function keeps a reference to count, so the variable outlives the call that created it and holds state between calls.
- Defer Runs LIFODeferred calls stack and run in reverse order when the function returns. Their arguments are evaluated immediately, not at run time.
Slices & Arrays · 4
- Growing A Sliceappend returns a new slice header, so you must assign the result back. Capacity grows in steps, usually doubling.
- Slices Share Backing ArraysSlicing does not copy. Both slices point at the same array, so writing through one is visible through the other.
- Copying To Break Aliasingcopy moves elements into a separate backing array, giving you an independent slice that can be mutated safely.
- Arrays Are ValuesAn array has a fixed length that is part of its type, and assigning one copies every element. Slices are the reference-like counterpart.
Maps · 3
- Creating A MapMaps are unordered key-value stores. Assigning inserts or overwrites, and delete removes a key without erroring if it is absent.
- Missing Key Returns ZeroReading an absent key yields the zero value rather than an error, so a stored zero is indistinguishable from missing without the comma-ok form.
- Writing To A Nil Map PanicsA nil map reads fine but panics on write. Always create one with make or a literal before assigning into it.
Structs · 3
- Defining A StructStructs group named fields. The %+v verb prints field names alongside values, which is far easier to read while debugging.
- Pointer vs Value ReceiversA value receiver works on a copy, so it cannot mutate. Use a pointer receiver whenever the method needs to change the struct.
- Struct EmbeddingEmbedding promotes the inner type's fields and methods to the outer one. It is composition, not inheritance, but reads similarly.
Interfaces · 3
- Interfaces Are ImplicitThere is no implements keyword. Any type with the right method set satisfies the interface automatically.
- Type SwitchA type switch recovers the concrete type behind an interface value and binds it to a correctly typed variable in each branch.
- Typed Nil Is Not NilAn interface holds a type and a value. A nil pointer stored in an interface makes the interface non-nil, a classic source of broken error checks.
Error Handling · 3
- Errors Are ValuesGo has no exceptions for ordinary failures. Functions return an error as the last value and callers check it explicitly.
- Wrapping With %wThe %w verb keeps the original error reachable. errors.Is then matches a sentinel through any depth of wrapping.
- Recover Inside Deferrecover only works inside a deferred function. Reserve panic for genuinely unrecoverable bugs, not for normal error paths.
Concurrency · 4
- WaitGroupgo starts a lightweight thread. A WaitGroup counts outstanding work so the caller can block until every goroutine finishes.
- Buffered ChannelA buffered channel accepts sends until it is full without a receiver. Ranging over a closed channel drains what is left, then stops.
- Select With Timeoutselect waits on several channel operations and runs whichever is ready first, which is the idiomatic way to add a timeout.
- Guarding Shared Statecounter++ is not atomic. Without the mutex the goroutines interleave and the total comes out short, a race the -race detector will flag.