Values and collections
| Pattern | What it does | Boundary to check |
|---|---|---|
v := value |
Declares a local variable with an inferred type | Short declaration needs a new name in its scope |
copy(dst, src) |
Copies up to the shorter length | Capacity alone does not give dst a length |
append([]int{}, src...) |
Copies integer elements into a result | Pointer elements still refer to shared objects |
value, ok := m[key] |
Returns value and key presence | A present zero differs from a missing key |
for k, v := range m |
Visits map entries | Iteration order is unspecified |
Methods, interfaces and errors
func (l *Ledger) Add(n int) { l.Used += n }
err := fmt.Errorf("manifest: %w", cause)
if errors.Is(err, cause) { /* handle the cause */ }
A pointer receiver can change the caller’s object. It does not add synchronization. An interface with a typed nil pointer can still be nonnil. %w preserves an error chain, while %v formats text. Use errors.As to retrieve documented fields from a typed error.
Generics and zero values
func First[T ~int | ~int64](values []T) (T, bool) {
var zero T
if len(values) == 0 { return zero, false }
return values[0], true
}
~int includes named types whose underlying type is int. The second result gives callers a clear empty-input contract. A numeric zero cannot represent absence when zero is valid data.
Concurrency and cleanup
| Pattern | Guarantee | Limit |
|---|---|---|
for v := range ch |
Stops after closure and buffered values | A nil channel blocks |
v, ok := <-ch |
Separates a received zero from closure | Shared ownership still needs a contract |
select { case <-ctx.Done(): ... } |
Offers a cancellation path | Multiple ready cases have no fixed priority |
mu.Lock() |
Coordinates callers using that mutex | Every access to protected state must cooperate |
defer closeResource() |
Runs cleanup when this function returns | Register it after successful acquisition |
Release the same mutex after the protected operation, including early return paths.
Native tool commands
go fmt ./... formats packages. go test ./... runs package tests. go test -race ./... instruments supported native targets for races. go test -bench . ./... runs benchmarks. These are native terminal commands, not commands exposed by this browser editor. Browser timing is not evidence of production throughput.
Try the Go exercises, review the interview questions or follow the course for progressively checked tasks.