CodeBlanks Logo Icon CodeBlanks

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())
    }
}

Practice 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.

Starter code

main.rs
struct Kutu {
    en: u32,
    boy: u32,
}

fn main() {
    // buraya yaz
}

Sample solution

main.rs
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());
}

Expected output

12 14

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if two separate <code>impl Kutu</code> blocks have a method with the same name <code>alan</code>?

  • Compile error: duplicate definition Correct answer
  • The later one overrides the earlier
  • Both are called
  • It becomes an overload

Explanation: Rust has no function overloading; two associated items with the same name for the same type is error E0592.

2 Call another method

Question
fn tanim(&self) -> String {
    format!("alan {}", ____.alan())
}
Answer
fn tanim(&self) -> String {
    format!("alan {}", self.alan())
}

Explanation: Another method of the same instance is called through self.

3 Case and result

Term Meaning
Two impl Kutu blocks Combined
Two methods with the same name E0592
self.alan() Inner call
impl Display for Kutu Trait implementation

All lessons in Beginner