Start learning free

LESSON 38 OF 69 · OBJECT-ORIENTED PROGRAMMING

Base Keyword in Rust: Extending a Parent Method with Traits

Practice Read the full explanation

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:

  1. trait Animal with two methods: fn bark(&self); and fn name(&self) -> &str;;
  2. struct Dog { name: String } and impl Animal for Dog: bark prints Woof! I am <name> with println!("Woof! I am {}", self.name);, and name returns &self.name;
  3. struct Puppy { name: String } and impl Animal for Puppy: its bark first prints the same Woof! I am <name> line, then Yip! Said <name>; name returns &self.name;
  4. fn mainFunction() and the first line of the driver, let buddy = Puppy {, which the driver then completes.

Notes:

  • impl Animal for Puppy gives Puppy the methods the trait asks for. Every method of the trait must be written.
  • {} inside println! is replaced by the next argument, here self.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();
  • buddy is a Puppy: its bark prints the parent's line, then its own.
  • rex is another Puppy: the names come from the object, nothing is hard-coded.
  • dog is a plain Dog: its bark is unchanged and prints only the parent's line, with no Yip!.

Expected output:

Woof! I am Buddy
Yip! Said Buddy
Woof! I am Rex
Yip! Said Rex
Woof! I am Max
STEP 1 OF 18
    Ctrl + Enter to check

    RUST · OBJECT-ORIENTED PROGRAMMING

    Base Keyword in Rust, explained

    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 name field. A struct can't borrow fields from another one, so Puppy declares its own String.
    • The puppy repeats the dog's line. With no super to call, Puppy::bark prints the Woof! 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

    1. Declare the trait Animal and close it right away, so the following steps go inside the braces.
    2. 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.
    3. List name. It takes &self and returns a &str, a borrowed view of text that the animal owns.
    4. Define the Dog struct with one field, name: String.
    5. Open impl Animal for Dog. This block is where Dog keeps its promise.
    6. Write bark with the same signature as in the trait, this time with a body.
    7. Print the dog's line with println!: {} is replaced by the next argument, self.name.
    8. Write name with the signature from the trait. Every method the trait lists must be written, or the code doesn't compile.
    9. Return a reference to self.name as the last expression, with no semicolon.
    10. Define the Puppy struct the same way, with its own name field.
    11. Open impl Animal for Puppy and write its bark signature.
    12. Print the dog's line first, which is the "parent" part, repeated by hand.
    13. Print the puppy's own line, Yip! Said and the name. Running the old behavior first and the new one second is what makes this an extension and not a replacement.
    14. Write the puppy's name method, returning &self.name.
    15. Declare mainFunction and start the first puppy with let 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.name becomes a &str. The field is a String, and the method promises a &str. Rust converts a reference to a String into a reference to its text automatically, so no .as_str() call is needed. The returned reference lives only as long as the borrow of self.
    • The last expression is the result. &self.name has 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's fn bark(&self);.
    • name is both a field and a method. That is allowed. buddy.name reads the field, and buddy.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 Dog has bark but no name, the compiler stops with error[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 Dog to yip. Dog and Puppy are separate types, so changing the puppy's bark never affects the dog: Max prints only the Woof! 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 Type block must write every method the trait doesn't already provide.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free