Idiomatic Rust replaces OOP inheritance and mutable shared state with composition, traits, and ownership rules to ensure memory safety without a garbage collector. Instead of defining a class hierarchy with extends, you define a struct for data and a trait for shared behavior, then implement the trait for your struct. Use &self for read-only access and &mut self for mutation, relying on the borrow checker to prevent data races at compile time.
struct Inventory {
shirts: Vec<String>,
}
trait Giveaway {
fn most_stocked(&self) -> String;
}
impl Giveaway for Inventory {
fn most_stocked(&self) -> String {
// Logic to find most stocked item
"Blue".to_string()
}
}