• Ephera
    link
    fedilink
    arrow-up
    2
    ·
    8 hours ago

    In Rust, as far as I understand anyway, traits define shared behavior.

    They’re certainly the concept closest to e.g. C#/Java interfaces. But you can also define shared behaviour with enums, as Rust’s enums are on steroids.

    Basically, let’s say you’ve got two existing types TypeA and TypeB for which you want to define shared behaviour.

    Then you can define an enum like so:

    enum SharedBehaviour {
        A(TypeA),
        B(TypeB),
    }
    

    And then you can define the shared behavior with an impl block on the enum:

    impl SharedBehaviour {
        pub fn greet(&self) {
            match self {
                SharedBehaviour::A(type_a) => println!("Hi there, {}!", type_a.name),
                SharedBehaviour::B(type_b) => println!("Hello, {}!", type_b.metadata.forename),
            }
        }
    }
    

    On the flipside, Rust doesn’t have superclasses/inheritance for defining shared behaviour.