make a class with inheritance in rust

To create a class with inheritance in rust, you can use traits and structs. Traits define a set of methods and properties that a type must implement, while structs define the properties and methods of a specific type. Here's an example:

main.rs
// Define a trait with methods that must be implemented by any struct that implements the trait
trait Animal {
    fn name(&self) -> String;
}

// Define a struct that implements the Animal trait
struct Dog {
    name: String,
    breed: String,
}

// Implement the Animal trait for the Dog struct
impl Animal for Dog {
    fn name(&self) -> String {
        self.name.clone()
    }
}

// Define a struct that inherits the properties of the Dog struct and adds an additional property
struct WorkingDog {
    dog: Dog,
    job: String,
}

// Implement the Animal trait for the WorkingDog struct by calling the name() method on the dog property
impl Animal for WorkingDog {
    fn name(&self) -> String {
        self.dog.name()
    }
}

// Create a WorkingDog instance and call the name() method (which is inherited from the Animal trait)
let my_dog = WorkingDog {
    dog: Dog {
        name: "Fido".to_string(),
        breed: "Golden Retriever".to_string(),
    },
    job: "Guide Dog".to_string(),
};

println!("My dog's name is {} and he is a {} that works as a {}.", my_dog.name(), my_dog.dog.breed, my_dog.job);
1118 chars
42 lines

This code defines two structs (Dog and WorkingDog) and a trait (Animal) that requires a name() method to be implemented. The Dog struct implements the Animal trait by defining the name() method, while the WorkingDog struct inherits the properties of the Dog struct and adds an additional job property. Finally, an instance of the WorkingDog struct is created and the name() method is called (which is inherited from the Animal trait).

gistlibby LogSnag