Start learning free

LESSON 641 OF 679 · OBJECT-ORIENTED PROGRAMMING

Method Overriding in Rust

Lesson

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, override or @Override. Puppy simply has its own impl method named bark, and Dog'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 fn in its impl Trait for Type block (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 Buddy
STEP 1 OF 2
    Ctrl + Enter to check