Difference between inferring and specifying type explicitly of let binding?


#1
fn main() {
   let mut x = 1;
   let y = &mut x;
   {
       //let z = y;
       let z: &mut i32 = y;
       *z = 2;
   }
   println!("{:?}", y);
}

Why line 6 is ok but not line 5? What is the difference? Thanks.


#2

This is a difference between moving and re-borrowing of mutable references:

let z = y; // this is a move because mutable references move (i.e. they're not copyable)
let z: &mut i32 = y; // this is an implicit reborrow
let z = &mut *y; // an explicit reborrow

Cannot infer appropriate lifetime for mutable reference
#3

Ok.

let z: &mut i32 = y; // this is an implicit reborrow

This is something new to me:) Get it. Thanks!


#4

Yeah - occasionally the compiler will move when you really want a reborrow. I think you’ll generally find an explicit reborrow used more often than the implicit one.

You may also find the following (related) blog post useful: https://bluss.github.io/rust/fun/2015/10/11/stuff-the-identity-function-does/