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