Default methods
- Rust course
- Intermediate
- Lesson 3/115
- 4 min
Define default methods in a trait.
Default methods
Trait methods can have a default body. An implementing type can use it as is or override it with its own version. Default methods can call the trait's other methods:
trait Tanit {
fn ad(&self) -> String;
fn selam(&self) -> String {
format!("Merhaba, ben {}", self.ad())
}
}This way the implementing type only needs to write ad; selam comes for free.
Override example
Two types implement the same trait; one uses the default, the other overrides it:
struct Robot;
struct Insan { ad: String }
impl Tanit for Robot {
fn ad(&self) -> String { String::from("R2") }
}
impl Tanit for Insan {
fn ad(&self) -> String { self.ad.clone() }
fn selam(&self) -> String {
format!("Selam! Ben {}.", self.ad)
}
}In the standard library Iterator is the best example: only next is written, and dozens of methods like map, filter and sum come by default.
Practice Introduction
Write the Tanit trait above, and the types Robot (uses the default, name "R2") and Insan (overrides selam). Print the results of Robot.selam() and Insan { ad: "Ece".to_string() }.selam() on separate lines.
Starter code
fn main() {
// buraya yaz
}Sample solution
trait Tanit {
fn ad(&self) -> String;
fn selam(&self) -> String {
format!("Merhaba, ben {}", self.ad())
}
}
struct Robot;
struct Insan {
ad: String,
}
impl Tanit for Robot {
fn ad(&self) -> String {
String::from("R2")
}
}
impl Tanit for Insan {
fn ad(&self) -> String {
self.ad.clone()
}
fn selam(&self) -> String {
format!("Selam! Ben {}.", self.ad)
}
}
fn main() {
println!("{}", Robot.selam());
println!("{}", Insan { ad: "Ece".to_string() }.selam());
}Expected output
Merhaba, ben R2 Selam! Ben Ece.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Can the default version be called from an overridden method?
- Only for generic types
- No; the overriding version fully replaces the default Correct answer
- Yes, with super.selam()
- Yes, always with Tanit::selam
Explanation: Rust has no inheritance; an overriding method can't reach the default body. Common code must go into a separate helper function.
2 Call the other method
fn selam(&self) -> String {
format!("Merhaba, ben {}", ____.ad())
}
fn selam(&self) -> String {
format!("Merhaba, ben {}", self.ad())
}
Explanation: A default method calls the same instance's other trait methods through self.
3 Case and result
| Term | Meaning |
|---|---|
Robot.selam() |
Default body |
Insan.selam() |
Overridden body |
Iterator::next |
Required method |
Iterator::map |
Default method |