RsRust

Rust: OOP – code examples

Contents

Struct + trait instead of a class

OOP#struct#impl#trait#oopCompare in all languages
Use case: Bundling data and behavior, e.g. users, products, game characters.
trait Tier {
    fn name(&self) -> &str;
    fn sprich(&self) -> String { format!("{} makes a sound", self.name()) }
}
struct Hund { name: String }
impl Tier for Hund {
    fn name(&self) -> &str { &self.name }
    fn sprich(&self) -> String { format!("{} says Woof!", self.name) }
}
fn main() {
    let rex = Hund { name: "Rex".to_string() };
    println!("{}", rex.sprich());
}

Rust has no classes and no inheritance: data lives in the struct, methods in the impl, and shared behavior (including a default implementation) in a trait. Without a trait, struct plus impl is enough.

Enum with data and match

OOP#enum#match#pattern
Use case: Modeling states or commands (commands, messages, parser tokens); the compiler checks every case.
enum Befehl {
    Start,
    Bewege { dx: i32, dy: i32 },
    Sage(String),
}

fn ausfuehren(b: Befehl) {
    match b {
        Befehl::Start => println!("Go!"),
        Befehl::Bewege { dx, dy } => println!("Move by {dx}/{dy}"),
        Befehl::Sage(text) => println!("Say: {text}"),
    }
}

fn main() {
    ausfuehren(Befehl::Start);
    ausfuehren(Befehl::Bewege { dx: 2, dy: -1 });
    ausfuehren(Befehl::Sage("Hi".to_string()));
}

Each variant carries its own data. If a case is missing from the match, the compiler reports an error, which is ideal when variants are added later.

Struct with derive and Default

OOP#derive#default#debug#struct
Use case: Configuration objects with sensible default values and simple debug output.
#[derive(Debug, Clone, PartialEq, Default)]
struct Einstellungen {
    titel: String,
    breite: u32,
    dunkel: bool,
}

fn main() {
    let basis = Einstellungen { titel: "App".to_string(), ..Default::default() };
    let angepasst = Einstellungen { breite: 800, ..basis.clone() };
    println!("{:?}", basis);
    println!("{:#?}", angepasst);
    println!("{}", basis == angepasst);
}

derive automatically generates debug output, cloning, comparison, and default values; .. fills in the remaining fields from another instance.