Rust
Default methods
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.
Exercise 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.
Show example 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());
}
Test yourself
-
Can the default version be called from an overridden method?
- Only for generic types
- No; the overriding version fully replaces the default
- Yes, with super.selam()
- Yes, always with Tanit::selam
Show answer
No; the overriding version fully replaces the default — Rust has no inheritance; an overriding method can't reach the default body. Common code must go into a separate helper function.
-
Call the other method
fn selam(&self) -> String {
format!("Merhaba, ben {}", ____.ad())
}
Show answer
fn selam(&self) -> String {
format!("Merhaba, ben {}", self.ad())
}
-
Case and result
- Robot.selam()
- Default body
- Insan.selam()
- Overridden body
- Iterator::next
- Required method
- Iterator::map
- Default method
Next lesson: Traits as parameters