FAQ - Help and questions

Rust has no classes or inheritance. What do I use instead?

#porting#traits#designpublished 3 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail
Last post

Short answer

Rust splits a class into data (a struct or enum) and behaviour (impl blocks and traits). Shared behaviour is a trait, a closed set of variants is an enum, and reuse of another type's code is done by holding it as a field. Which one fits depends on whether the set of types is open or closed.

Checked with rustc 1.93.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

There is no class Dog : Animal. Three tools replace it, and each is the right choice in a different situation. The answers below show each as its own complete example; all three compiled and ran with rustc 1.93.0.

You wantUse
Different types with the same operations, and new types may be added latera trait
A fixed, known set of variantsan enum
To reuse the code and data of another typecomposition: hold it as a field

Common mistakes#

  • Looking for a base-class field to inherit. Traits have no fields; put shared data in a struct and share it by composition.
  • Using Box<dyn Trait> when an enum would do. Enums are simpler and let match check that every case is handled.
  • Copying a class hierarchy of five levels. Flatten it: most levels existed only to share code.

Can a trait have default method bodies?#

Yes. A default method works like a virtual method with a body, and each type can override it.

What is the difference between dyn Trait and a generic T: Trait?#

A generic is resolved at compile time and produces code for each type. dyn Trait is resolved at run time through a vtable and lets one collection hold different types.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    3 answers from the Ruststudio team: different approaches, each with its own trade-offs

    Sort: Oldest Newest
    #2

    Approach 1: a trait for shared behaviour#

    Use a trait when callers need "anything that can do X" and more types may be added later, including by other crates.

    rust
    trait Animal {
        fn name(&self) -> String;
        fn sound(&self) -> String;
        fn describe(&self) -> String {
            format!("{} says {}", self.name(), self.sound()) // default method
        }
    }
    struct Dog;
    struct Cat {
        indoor: bool,
    }
    impl Animal for Dog {
        fn name(&self) -> String { "Dog".into() }
        fn sound(&self) -> String { "woof".into() }
    }
    impl Animal for Cat {
        fn name(&self) -> String { if self.indoor { "House cat".into() } else { "Cat".into() } }
        fn sound(&self) -> String { "meow".into() }
    }
    
    fn main() {
        let zoo: Vec<Box<dyn Animal>> = vec![Box::new(Dog), Box::new(Cat { indoor: true })];
        for a in &zoo {
            println!("{}", a.describe());
        }
    }
    text
    Dog says woof
    House cat says meow

    Trade-off: calls through dyn Animal go through a vtable, and the trait carries no data.

      QuoteReply
      Share
      Hacker NewsRedditLinkedInE-mail
      #3

      Approach 2: an enum for a closed set#

      Use an enum when all variants are known in one place. match must handle every variant, so adding one produces compile errors at each place that needs updating.

      rust
      enum Shape {
          Circle { radius: f64 },
          Rect { w: f64, h: f64 },
      }
      
      impl Shape {
          fn area(&self) -> f64 {
              match self {
                  Shape::Circle { radius } => std::f64::consts::PI * radius * radius,
                  Shape::Rect { w, h } => w * h,
              }
          }
      }
      
      fn main() {
          let shapes = [Shape::Circle { radius: 1.0 }, Shape::Rect { w: 2.0, h: 3.0 }];
          for s in &shapes {
              println!("{:.2}", s.area());
          }
      }
      text
      3.14
      6.00

      Trade-off: nobody outside the enum's crate can add a variant.

        QuoteReply
        Share
        Hacker NewsRedditLinkedInE-mail
        #4

        Approach 3: composition instead of "extends"#

        Use composition to reuse code and data. The "derived" type holds the "base" type as a field and calls it; an override is a new method that calls the old one.

        rust
        struct Employee {
            name: String,
            salary: u32,
        }
        impl Employee {
            fn pay(&self) -> u32 {
                self.salary
            }
        }
        
        struct Manager {
            employee: Employee,
            reports: Vec<Employee>,
        }
        impl Manager {
            fn pay(&self) -> u32 {
                self.employee.pay() + 100 * self.reports.len() as u32
            }
        }
        
        fn main() {
            let m = Manager {
                employee: Employee { name: "Ada".into(), salary: 5000 },
                reports: vec![Employee { name: "Bo".into(), salary: 3000 }],
            };
            println!("{} earns {}", m.employee.name, m.pay());
        }
        text
        Ada earns 5100

        Trade-off: you write the forwarding methods yourself. Combine with a trait if callers need to treat both types the same way.

          QuoteReply
          Share
          Hacker NewsRedditLinkedInE-mail