Consider the following program:
use std::ops::DerefMut;
struct St;
trait Tr { }
impl Tr for St { }
fn make_it() -> Box<Tr> {
Box::new(St)
}
fn take_it(_: &mut Tr) {
}
fn main() {
let mut oracle = make_it();
//take_it(&mut *oracle); // WORKS
//take_it(oracle.deref_mut()); // ERROR
}
I don't understand why the first invocation of take_it()
works, while the second one yields a compiler error. The error is:
src/main.rs:19:13: 19:19 error: `oracle` does not live long enough
src/main.rs:19 take_it(oracle.deref_mut()); // ERROR
^~~~~~
src/main.rs:16:11: 20:2 note: reference must be valid for the block at 16:10...
src/main.rs:16 fn main() {
src/main.rs:17 let mut oracle = make_it();
src/main.rs:18 //take_it(&mut *oracle); // WORKS
src/main.rs:19 take_it(oracle.deref_mut()); // ERROR
src/main.rs:20 }
src/main.rs:17:32: 20:2 note: ...but borrowed value is only valid for the block suffix following statement 0 at 17:31
src/main.rs:17 let mut oracle = make_it();
src/main.rs:18 //take_it(&mut *oracle); // WORKS
src/main.rs:19 take_it(oracle.deref_mut()); // ERROR
src/main.rs:20 }
error: aborting due to previous error
I would have expected the two lines to be pretty much equivalent -- the second being a desugaring of the first.
Rust 1.8.0.