How reborrowing works?

There are a few basic rules you can use to understand this:

  1. Reference assigned to an &mut _ will be reborrowed. Examples:
let mut a = 6;
let b = &mut a;
let c: &mut i32 = b; // equals `&mut *b`, a reborrow of `a`.

// will reborrow as well
fn myfn(x:&mut i32){

}

As said above, it fails in a case like:

fn foo<T>(_: T) {}

because T isn't necessarily a ref type. This means that instead of reborrowing, it is moved (and because it is a mutable ref, that does not implement Copy.)

It is even more confusing with 2 types, but leave that aside for now.

If you give enough info, the compiler can infer that it is type of &mut i32 . Just like jonh did.

A summary can be found here.

There are also these exercises published today in the forum: Subtle borrowing behavior example.

1 Like