Rust
Multiple impl blocks
Write multiple impl blocks for a single struct.
Multiple impl blocks
A type can have several impl blocks; the compiler combines them all. This is used to group constructors, calculations and helpers separately:
impl Kutu {
fn new(en: u32, boy: u32) -> Self { Self { en, boy } }
}
impl Kutu {
fn alan(&self) -> u32 { self.en * self.boy }
fn kenar_toplami(&self) -> u32 { 2 * (self.en + self.boy) }
}
Separate blocks become especially meaningful for trait implementations (impl Display for Kutu) and conditional generic implementations.
Calling methods inside methods
A method can call other methods of the same type with self.; this also holds for methods in different blocks:
impl Kutu {
fn kare_mi(&self) -> bool {
self.en == self.boy
}
fn tanim(&self) -> String {
let tur = if self.kare_mi() { "kare" } else { "dikdörtgen" };
format!("{tur}, alan {}", self.alan())
}
}
Exercise Two blocks
Write new in a first impl Kutu block, and the methods alan and kenar_toplami (2 × (en + boy)) in a second block. Print both results for Kutu::new(3, 4) separated by a space.
Show example solution
struct Kutu {
en: u32,
boy: u32,
}
impl Kutu {
fn new(en: u32, boy: u32) -> Self {
Self { en, boy }
}
}
impl Kutu {
fn alan(&self) -> u32 {
self.en * self.boy
}
fn kenar_toplami(&self) -> u32 {
2 * (self.en + self.boy)
}
}
fn main() {
let k = Kutu::new(3, 4);
println!("{} {}", k.alan(), k.kenar_toplami());
}
Test yourself
-
What happens if two separate <code>impl Kutu</code> blocks have a method with the same name <code>alan</code>?
- Compile error: duplicate definition
- The later one overrides the earlier
- Both are called
- It becomes an overload
Show answer
Compile error: duplicate definition — Rust has no function overloading; two associated items with the same name for the same type is error E0592.
-
Call another method
fn tanim(&self) -> String {
format!("alan {}", ____.alan())
}
Show answer
fn tanim(&self) -> String {
format!("alan {}", self.alan())
}
-
Case and result
- Two impl Kutu blocks
- Combined
- Two methods with the same name
- E0592
- self.alan()
- Inner call
- impl Display for Kutu
- Trait implementation
Next lesson: Summary - Methods