I'm trying to understand how Rust decides between moving and borrowing references when they are given as arguments to a generic function.
I think my confusion comes what appears to be a contradiction in whether a generic type T
binds to the value or reference type, as in the example below. If it's the value then it should be able to successfully copy it, or if it's the reference it should be able to borrow it, however the results make it seem like neither of these are the case.
use std::borrow::BorrowMut;
fn main() {
let mut value: u32 = 0;
let reference: &mut u32 = &mut value;
// Okay, function borrows the reference.
reference_arg(reference);
// Okay, should be exactly the same as above.
generic_arg::<&mut u32>(reference);
// Not okay, tries to move the reference, but why?
// generic_arg(reference);
// Okay, but why is it different from the above?
generic_arg(reference.borrow_mut());
// Check original reference hasn't been moved from.
*reference = 1;
}
fn reference_arg(_arg: &mut u32) {
// NOOP
}
fn generic_arg<T>(_arg: T) {
// NOOP
}