Basic Object Oriented Programming in Rust

⚓ Rust    📅 2026-03-23    👤 surdeus    👁️ 2      

surdeus

I come from the Java world so please excuse me as a complete Rust noob.
In my OO-stuff, there are common methods as well as object-type-specific ditto. I have in this example showed how I wanted to do this in Rust but failed.

trait Speak {
    fn speak(&self) -> String;
}

enum Animal {
    Dog(Dog),
    Cat(Cat)
}

struct Dog {

}

impl Dog {
    fn only_for_dogs() {

    }
}

impl Speak for Dog {
    fn speak(&self) -> String {
        String::from("Bark")
    }
}

struct Cat {

}

impl Speak for Cat {
    fn speak(&self) -> String {
        String::from("Meow")
    }
}

impl Speak for Animal {
    fn speak(&self) -> String {
        // This is obviously entirely wrong, it is recursion!
        self.speak()
    }
}

fn main() {
    let dog = Animal::Dog(Dog{});
    println!("Animal says: {}", dog.speak());
    // How can you call the "only_for_dogs()" method
    // from an Animal variable including telling the
    // caller that the method in unavailable in case
    // the call was made from a Cat instance.
}

9 posts - 6 participants

Read full topic

🏷️ Rust_feed