How the rust how to lookup method for different object

fn main() {
    let mut s1 = Struct {};
    s1.print_ref();
    s1.print_mut_ref();
    s1.print_self();

    println!("----------------");

    let r1 = &mut Struct {};
    r1.print_ref();
    r1.print_mut_ref();
    r1.print_self();

    println!("----------------");

    let r2 = &Struct {};
    r2.print_ref();
    // r2.print_mut_ref();
    r2.print_self();

    println!("----------------");

    let mut r3 = &Struct {};
    r3.print_ref();
    r3.print_mut_ref();
    r3.print_self();

    r3 = &Struct {};
}

trait Trait {
    fn print_self(self);
    fn print_ref(&self);
    fn print_mut_ref(&mut self);
}

#[derive(Debug)]
struct Struct {}

impl Trait for Struct {
    fn print_self(self) {
        println!("Struct self");
    }

    fn print_ref(&self) {
        println!("Struct &self")
    }

    fn print_mut_ref(&mut self) {
        println!("Struct $mut self");
    }
}

impl Trait for &Struct {
    fn print_mut_ref(&mut self) {
        println!("$Struct &mut self");
    }

    fn print_ref(&self) {
        println!("$Struct &self");
    }

    fn print_self(self) {
        println!("$Struct self");
    }
}

impl Trait for &mut Struct {
    fn print_self(self) {
        println!("$mut Struct self");
    }

    fn print_ref(&self) {
        println!("$mut Struct &self");
    }

    fn print_mut_ref(&mut self) {
        println!("$mut Struct &mut self");
    }
}

the answer is

Struct &self
Struct $mut self
Struct self
----------------
$mut Struct &self
Struct $mut self
$mut Struct self
----------------
Struct &self
$Struct self
----------------
Struct &self
$Struct &mut self
$Struct self

Please properly format your code as per this pinned topic. You can run it through Tools: Rustfmt on the playground first if needed.


Here's the documentation on how method resolution works.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.