Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Flexibility in Signatures

Rust has several ways to write code that works with more than one type. Each is a different design commitment:

MechanismDispatchSet of typesReads as
enummatchClosed: you list the variants“These, and only these.”
Generics <T: Trait>StaticOpen, fixed at compile time“Anything with this capability, known now.”
dyn TraitDynamicOpen, chosen at runtime“Anything with this capability, chosen later.”
CompositionNoneNot polymorphism“This is made of parts.”

A decision procedure, usable in review and in prompts:

  1. Do you control the full set of variants, and is it small and stable? Use an enum. As long as matches avoid _ arms, adding a variant produces a compile error everywhere it’s not handled.
  2. Do downstream users need to plug in their own types? Use a trait. Prefer generics; use dyn for heterogeneous collections or to keep type parameters out of a public signature.
  3. Is the relationship just “has-a”? Use composition.

In trait definitions

  • A generic parameter on the trait (trait Store<V>) allows one type to implement the trait several times, once per V.
  • An associated type (trait Store { type V; }) allows one implementation with one choice of V. This is usually what you want.