TL ; DR:
In languages with class inheritance, a child class that defines a method with the same name as the parent's overrides it. Rust has no inheritance, so the idea shows up in two ways: a type defining its own method with the same name, or a type replacing a trait's default method. Different types can give the same method name different behavior.
trait Animal {
fn bark(&self) { println!("Woof!"); }
}
struct Dog;
impl Animal for Dog {}
struct Puppy;
impl Animal for Puppy {
fn bark(&self) { println!("Yip!"); }
}
Full lesson:
You've seen that a Puppy can reuse a Dog's behavior by holding one and forwarding calls to it. Overriding is what happens when the puppy wants to change that behavior instead of forwarding it.
Why override?
A Puppy is a special kind of Dog, but it sounds different — "Yip!" instead of "Woof!". Instead of inventing a new method name, you define bark() on the Puppy too. Callers just call bark() and the version belonging to the value's own type runs.
How it works in Rust
- No keywords — there is no
virtual,overrideor@Override.Puppysimply has its ownimplmethod namedbark, andDog's method is a different function on a different type. - Trait default methods — a trait can give a method a default body, and a type that implements the trait can replace it by writing its own
fnin itsimpl Trait for Typeblock (the TL;DR example above).
Your task
The Dog struct already has a bark method. Inside the impl Puppy block, add a bark method of its own so it prints "Yip! I am " followed by the puppy's name. The code in main_function creates a Puppy named "Buddy" and calls bark() on it.
Expected output:
Yip! I am BuddyFree plan: 30 tutor messages. PRO is unlimited.
