Problem overview
In languages with classes, a child class often extends a parent's method: it runs the parent's version first and then adds something of its own. Rust has no class inheritance and no super or base keyword, so this lesson shows how the same idea looks in Rust.
You write a small program with three parts: a trait Animal, a struct Dog and a struct Puppy. A dog barks Woof! I am <name>. A puppy barks the same line and then adds Yip! Said <name>. At the end you write the first line of mainFunction, and the starter code completes it: it makes two puppies and a dog and calls bark on each. The expected output is:
Woof! I am Buddy
Yip! Said Buddy
Woof! I am Rex
Yip! Said Rex
Woof! I am Max
Approach: a trait instead of a parent class
A trait is a list of methods that different types can promise to provide. Dog and Puppy are two unrelated structs. Neither one is the parent of the other, and neither inherits fields from the other. They are connected only because both write impl Animal for ....
That has two consequences for this lesson:
- Each struct has its own
namefield. A struct can't borrow fields from another one, soPuppydeclares its ownString. - The puppy repeats the dog's line. With no
superto call,Puppy::barkprints theWoof!line itself and then prints its own line. The "parent behavior" is copied by hand.
The trait is what lets code treat both types the same way. Anything that needs an Animal only cares that bark and name exist.
Step by step
- Declare the trait
Animaland close it right away, so the following steps go inside the braces. - List
bark. It takes&self(a read-only borrow of the animal) and returns nothing. In a trait, the line ends with a semicolon because the trait gives no body. - List
name. It takes&selfand returns a&str, a borrowed view of text that the animal owns. - Define the
Dogstruct with one field,name: String. - Open
impl Animal for Dog. This block is whereDogkeeps its promise. - Write
barkwith the same signature as in the trait, this time with a body. - Print the dog's line with
println!:{}is replaced by the next argument,self.name. - Write
namewith the signature from the trait. Every method the trait lists must be written, or the code doesn't compile. - Return a reference to
self.nameas the last expression, with no semicolon. - Define the
Puppystruct the same way, with its ownnamefield. - Open
impl Animal for Puppyand write itsbarksignature. - Print the dog's line first, which is the "parent" part, repeated by hand.
- Print the puppy's own line,
Yip! Saidand the name. Running the old behavior first and the new one second is what makes this an extension and not a replacement. - Write the puppy's
namemethod, returning&self.name. - Declare
mainFunctionand start the first puppy withlet buddy = Puppy {. The starter code finishes the rest.
The solution in Rust
trait Animal {
fn bark(&self);
fn name(&self) -> &str;
}
struct Dog {
name: String,
}
impl Animal for Dog {
fn bark(&self) {
println!("Woof! I am {}", self.name);
}
fn name(&self) -> &str {
&self.name
}
}
struct Puppy {
name: String,
}
impl Animal for Puppy {
fn bark(&self) {
println!("Woof! I am {}", self.name);
println!("Yip! Said {}", self.name);
}
fn name(&self) -> &str {
&self.name
}
}
fn mainFunction() {
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();
}
Details worth knowing
&self.namebecomes a&str. The field is aString, and the method promises a&str. Rust converts a reference to aStringinto a reference to its text automatically, so no.as_str()call is needed. The returned reference lives only as long as the borrow ofself.- The last expression is the result.
&self.namehas no semicolon, so the method returns it. Adding a semicolon would make the method return()and the code would not compile. - The signature must match the trait.
fn bark(&self)in the impl block has to agree with the trait'sfn bark(&self);. nameis both a field and a method. That is allowed.buddy.namereads the field, andbuddy.name()calls the trait method.
A variation: a default method
A trait can supply a body for a method. Types that don't write their own version get it for free. Here Dog uses the default bark and Puppy replaces it:
trait Animal {
fn name(&self) -> &str;
fn bark(&self) {
println!("Woof! I am {}", self.name());
}
}
struct Dog { name: String }
struct Puppy { name: String }
impl Animal for Dog {
fn name(&self) -> &str { &self.name }
}
impl Animal for Puppy {
fn name(&self) -> &str { &self.name }
fn bark(&self) {
println!("Woof! I am {}", self.name());
println!("Yip! Said {}", self.name());
}
}
fn main() {
let zoo: Vec<Box<dyn Animal>> = vec![
Box::new(Dog { name: "Max".to_string() }),
Box::new(Puppy { name: "Buddy".to_string() }),
];
for x in &zoo {
x.bark();
}
}
It prints:
Woof! I am Max
Woof! I am Buddy
Yip! Said Buddy
Even here, the puppy's override can't call the trait's default body. An override replaces the default completely, so the shared line is written again. When the shared part is long, move it into a plain function that both bark methods call.
Edge cases and common mistakes
- Forgetting a trait method. If
impl Animal for Doghasbarkbut noname, the compiler stops witherror[E0046]: not all trait items implemented, missing: `name`. - Hard-coding names. The two puppies print different names because every line uses
self.name. A literal"Buddy"would break the second one. - Replacing instead of extending. If the puppy printed only the
Yip!line, it would override the dog's behavior, not extend it. The driver's first two puppies show both lines. - Expecting a plain
Dogto yip.DogandPuppyare separate types, so changing the puppy'sbarknever affects the dog:Maxprints only theWoof!line.
Key takeaways
- Rust shares behavior through traits, not through parent classes.
- To extend behavior, run the old steps again (or call a shared function) and then add the new ones.
- Each struct owns its own fields, and an
impl Trait for Typeblock must write every method the trait doesn't already provide.
