Design small interfaces and safe slices
Keep dependencies testable and avoid accidental backing-array sharing.
Describe behavior where it is used
An interface is valuable when a consumer needs a small set of operations, such as Find or Save. Define that interface near the consumer rather than creating a broad interface for every method on a concrete type. A fake in a test should implement only the operations the unit truly uses.
Know what a slice shares
A slice is a descriptor over an underlying array. Slicing or appending may share storage, so changing a filtered result can unexpectedly change the input. Allocate a new result when independence is part of the contract. Test the values and whether modifying the result leaves the input unchanged.
out := make([]int, 0, len(in))
for _, value := range in {
if value > 0 { out = append(out, value) }
}
Name the ownership rule
A function that edits its input can be efficient, but its name or documentation should make mutation clear. For library code, predictability often outweighs a small allocation. Table-driven tests should cover empty input, all filtered values, and a result changed after the call.
Check your understanding
Why can `out := in[:0]` surprise a caller?
Show explanation
It reuses the input's backing array, so appending to out can overwrite values visible through in.
You can read for free. Create an account to save your progress.
← Previous lesson: Return useful Go errors Next lesson: Carry cancellation through Go services →Put this lesson into practice
A practice activity at this level in the same module.
Try: Filter a slice into a new backing arrayFurther reading
Primary references for this module. Check the current version when behavior or framework guidance may have changed.