Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert T to &mut T with `.`?

According to my understanding, next needs a &mut Test, but create_test() returns a Test.

Why can this be compiled?

My guess is that . will implicitly convert Test to &mut Test, I am not sure. Can somebody explain more about this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

pub struct Test {
    t: u64,
}

fn create_test() -> Test {
    Test {
        t: 1
    }
} 

impl Test {
    pub fn next(&mut self) {
        self.t = 10;
    }
}

fn main() {
    let mut t = Test { t: 20 };
    t.next();

    create_test().next();  // here
}

>Solution :

This is explained in the Method-call expressions section of the book.

When looking up a method call, the receiver may be automatically dereferenced or borrowed in order to call a method.

This is exactly what is happening here. The rust compiler is automatically borrowing value returned create_test.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading