1

When does function reborrow / move its argument? In the following example,

fn main() {
    use std::str::FromStr;
    let mut my_str: String = String::from_str("hello").unwrap();
    let borrow_str: &mut String = &mut my_str;
    foo(borrow_str);
    println!("{}", borrow_str)
}


fn foo<T>(string: &mut T) {} // works. reborrows &mut String.
// fn foo<T>(string: T) {} // does not work. moves &mut String.

Why do they work differently?

Playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=b157c254f9a88efd69099dce1bb41de4

j.s.shin
  • 11
  • 2
  • This is a common question. Mutable reference assignments are a bit magic. The reborrow happens when the compiler already knows that the target type is a mutable reference. If this is only inferred later, no reborrow is applied. – Sven Marnach Oct 28 '22 at 07:22
  • Thanks! The linked post answers my question perfectly, even though the question is not exactly the same. `fn bar(_a: T, _b: T) {}` example really blows my mind. – j.s.shin Oct 28 '22 at 07:51

0 Answers0