Traits Are Interface Types

  • Define methods, fields and types that must be present in the implementation of a struct or enum

  • Principal mechanism for code reuse in Rust

  • Interact strongly with and enhance "generic" types (parametric polymorphism)

Defining A Trait

Trait Bounds vs Trait Objects

The Orphan Rules

  • Idea: When you call something like foo.bar() where foo is a trait object, the compiler needs to know what implementation of bar() to use.

  • Consider one crate providing

     impl ToString for u32 {
          fn to_string(x: &u32) -> String {
             format!("{}!", x)
          }
     }
    

    and another

     impl ToString for u32 {
          fn to_string(x: &u32) -> String {
             format!("{}?", x)
          }
     }
    
  • "Orphan Rules" forbid implementing another crate's trait on another trait's type (or thereabouts) to solve this problem

  • The details are complicated

  • Technical discussion

Subtraits

  • You can insist on some trait requiring all the methods of another trait

  • For example, std has trait Copy: Clone

    • This means that anything that is Copy must also be Clone

    • It also guarantees implementations of Copy access to Clone methods on self

Last modified: Monday, 3 February 2020, 4:20 PM