BorrowCheck › Rust language core

Traits, generics, dyn / impl

Defining traits, monomorphization, dyn Trait vs impl Trait, object safety, coherence.

The topic explains traits as a description of shared behavior and generics as a way to write code for many types at once. The questions check the rules for implementing and calling: a trait must be in scope, an inherent method takes priority over a trait method, and a name clash calls for a fully qualified path. The generics subtopic covers trait bounds and monomorphization: the compiler produces a separate copy of a function for each set of types, gaining speed at the cost of code size. Next, impl Trait is compared with dyn Trait: a single hidden concrete type versus a trait object with a vtable, which leads to the dyn-compatibility rules for methods involving Self, generic parameters and the where Self: Sized clause. The coherence subtopic explains the orphan rule, blanket implementations, and the newtype wrapper for a foreign trait on a foreign type. The last subtopic is about default methods and supertraits: what a bound on a subtrait provides and when the supertrait must be implemented as well.

39 questions: 18 basic, 17 intermediate, 4 advanced. 6 info pages, 25 sources.

Subtopics

  1. Defining and implementing traits
  2. Generics and monomorphization
  3. dyn Trait vs impl Trait
  4. Object safety (dyn-compatibility)
  5. Coherence and the orphan rule
  6. Default methods and supertraits

Previous: Strings and text · Next: Associated types, GATs, const generics