Select useful library abstractions
Select useful library abstractions
Choose a collection by its operations and contract, not by familiarity. A slice suits indexed access and compact traversal, a map suits key lookup, a list suits moving known nodes, and a heap suits repeated selection of the next priority. Prefer a simple built-in or library implementation before writing custom storage. Measure representative workloads when performance matters.
package main
import ( "fmt" "maps" "slices")
func report(words []string) []string { counts := map[string]int{} for _, w := range words { counts[w]++ } keys := slices.Sorted(maps.Keys(counts)) out := make([]string, 0, len(keys)) for _, k := range keys { out = append(out, fmt.Sprintf("%s:%d", k, counts[k])) } return out}func main() { fmt.Println(report([]string{"tea", "rice", "tea"})) fmt.Println(len(report(nil)))}The map aggregates counts, the sorted keys provide stable ordering, and the returned slice stores the report. Each structure has a separate job. The map stays inside the function, so callers cannot mutate its entries. The function returns an empty report for empty input.
Expected output:
[rice:1 tea:2]0Choose explicit copy semantics
package main
import ( "fmt" "slices")
type Store struct{ values []int }
func (s *Store) Add(v int) { s.values = append(s.values, v) }func (s *Store) Snapshot() []int { return slices.Clone(s.values) }func main() { var s Store s.Add(4) s.Add(8) b := s.Snapshot() b[0] = 9 fmt.Println(s.Snapshot(), b)}Snapshot returns independent integer storage; returning s.values directly would expose a mutable view. The zero value of Store works because append accepts a nil slice. A copy is shallow for reference-bearing elements and costs time and memory proportional to the slice length. This Store is not safe for concurrent mutation without synchronization. State the ownership and concurrency contract rather than assuming library helpers solve it.
Expected output:
[4 8] [9 8]Try it locally
Write uniqueSorted that uses a map[int]struct{} for membership and slices.Sorted(maps.Keys(...)) for output. Print the result for [3,1,3,2] and the length for nil input.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Core library 07: Select useful library abstractions
Check the lesson objective before moving on.
Which structure suits grouping arbitrary keys into counts?
What does returning slices.Clone of a slice of ints provide?