TL ; DR:
Rust has no class inheritance and no super. Shared behavior is described by a trait: Dog and Puppy are separate structs that both implement the trait Animal. A Puppy that wants to "extend" the dog's bark simply does what Dog's bark does first (the same println!) and then adds its own line.
impl Animal for Puppy {
fn bark(&self) {
println!("Woof! I am {}", self.name); // what Dog's bark prints
println!("Yip! Said {}", self.name);
}
fn name(&self) -> &str {
&self.name
}
}
Why it matters
Overriding a method replaces the parent's behavior. Often you want to extend it instead: keep what the parent did and add something more. A typical example is a save method: the parent writes the row to the database, and a subclass runs the parent's save first and then writes a log line.
Your task
There are no classes to extend here, so you write the whole program above the driver, in order:
trait Animalwith two methods:fn bark(&self);andfn name(&self) -> &str;;struct Dog { name: String }andimpl Animal for Dog:barkprintsWoof! I am <name>withprintln!("Woof! I am {}", self.name);, andnamereturns&self.name;struct Puppy { name: String }andimpl Animal for Puppy: itsbarkfirst prints the sameWoof! I am <name>line, thenYip! Said <name>;namereturns&self.name;fn mainFunction()and the first line of the driver,let buddy = Puppy {, which the driver then completes.
Notes:
impl Animal for PuppygivesPuppythe methods the trait asks for. Every method of the trait must be written.{}insideprintln!is replaced by the next argument, hereself.name.
The driver (already written, it runs when you press Run):
let buddy = Puppy {
name: "Buddy".to_string(),
};
buddy.bark();
let rex = Puppy { name: "Rex".to_string() };
rex.bark();
let dog = Dog { name: "Max".to_string() };
dog.bark();
buddyis aPuppy: itsbarkprints the parent's line, then its own.rexis anotherPuppy: the names come from the object, nothing is hard-coded.dogis a plainDog: itsbarkis unchanged and prints only the parent's line, with noYip!.
Expected output:
Woof! I am Buddy
Yip! Said Buddy
Woof! I am Rex
Yip! Said Rex
Woof! I am Max
Free plan: 30 tutor messages. Premium is unlimited.
