Design generic collections and zero values
Design generic collections and zero values
A generic collection should have a useful zero value where practical and explicitly report empty lookups. Declare var zero T to obtain the zero value of an arbitrary type parameter. Returning zero alone cannot distinguish an empty collection from a stored zero. A boolean result is one clear contract.
package main
import ( "fmt")
type Stack[T any] struct{ items []T }
func (s *Stack[T]) Push(v T) { s.items = append(s.items, v) }func (s *Stack[T]) Pop() (T, bool) { n := len(s.items) if n == 0 { var z T return z, false } v := s.items[n-1] var z T s.items[n-1] = z s.items = s.items[:n-1] return v, true}func main() { var s Stack[int] fmt.Println(s.Pop()) s.Push(0) s.Push(7) fmt.Println(s.Pop()) fmt.Println(s.Pop()) fmt.Println(s.Pop())}The nil slice in the zero-valued Stack accepts append. Pop clears the removed slot before reslicing, which can avoid retaining references in the backing array. It does not guarantee immediate garbage collection. Do not copy a populated stack and assume independent backing storage; concurrent mutation requires synchronization.
Expected output:
0 false7 true0 true0 falseInitialize a map lazily
package main
import ( "fmt")
type Set[T comparable] struct{ items map[T]struct{} }
func (s *Set[T]) Add(v T) { if s.items == nil { s.items = make(map[T]struct{}) } s.items[v] = struct{}{}}func (s Set[T]) Has(v T) bool { _, ok := s.items[v]; return ok }func main() { var s Set[string] fmt.Println(s.Has("a")) s.Add("a") s.Add("a") fmt.Println(s.Has("a"), len(s.items))}Nil map reads are safe, but writes need initialization. Add allocates only when needed. The zero-sized struct value records membership. The comparable constraint allows map keys; interface keys with dynamically noncomparable values can still panic. This small set is not concurrency-safe.
Expected output:
falsetrue 1Try it locally
Implement Slot[T any] with Value T and Present bool, and Get() (T,bool). For a zero-valued Slot[string] and a present empty string print the quoted value and boolean.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Generics 10: Design generic collections and zero values
Check the lesson objective before moving on.
How do you obtain the zero value of unconstrained T?
Why return a boolean from Pop?