Guy Korland
Guy Korland

Reputation: 9568

Why calling method on self doesn't cause recursion in Rust?

How come the code bellow doesn't cause an endless recursion? I would expect the impl of FFF for is_empty calling self.is_empty() will cause endless recursion and not call the impl of Foo.

struct Foo{}

impl Foo{
    pub fn is_empty(&self) -> Option<bool>{
        Some(true)
    }
}

trait FFF {
    fn is_empty(&self) -> Option<bool>;
}

impl FFF for Foo {
    fn is_empty(&self) -> Option<bool>{
        println!("calling FFF");
        self.is_empty()    
    }
}

fn pr<F:FFF>(a:F){
  println!("{:?}", a.is_empty());
}

fn main() {
    pr(Foo{});
    
}

Output:

calling FFF
Some(true)

Upvotes: 1

Views: 190

Answers (1)

Chayim Friedman
Chayim Friedman

Reputation: 71350

Method resolution always prefers inherent methods. See also the reference.

Upvotes: 3

Related Questions