Difference between inferring and specifying type explicitly of let binding?

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.

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

Ok.

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

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

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: Stuff the Identity Function Does (in Rust)