4

Consider this code:

struct A;

trait Test {
    fn test(self);
}

impl Test for &mut A {
    fn test(self) {
        println!("&mut Test called");
    }
}

fn test(a: &mut A) {
    a.test();
}

fn test2(a: impl Test) {
    a.test();
}

fn main() {
    let mut a = A;

    let a_mut_ref = &mut a;

    test(a_mut_ref); // works fine
    test(a_mut_ref); // works fine

    test2(a_mut_ref); // `a_mut_ref` moved here? Why?
    test2(a_mut_ref); // compile error `use of moved value` here
}

According to Rust's docs, mutable references do not implement Copy.

  1. Why does calling test twice work fine?
  2. Why does not it work with test2 the same way?
  3. How can I change test2 to keep both impl-like boundary and get successful compilation?
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Dmitry
  • 1,426
  • 5
  • 11
  • 3
    Look up [reborrow](https://doc.rust-lang.org/1.12.0/nomicon/references.html#liveness), currently still [lacking](https://github.com/rust-lang/reference/issues/788) in docs. – user4815162342 Mar 29 '21 at 21:36
  • 2
    It's complicated – Stargateur Mar 29 '21 at 21:38
  • Update definition of `test2` to `fn test2(a: T)`, then you'll see a better error message for your question. – Ömer Erden Mar 29 '21 at 21:38
  • **1** reborrows, as linked previously and explained in the duplicates. **2** Because `impl Trait` introduces a generic, and further explained in the duplicates. **3** you cannot currently, as explained in the duplicates. – Shepmaster Mar 29 '21 at 23:49

0 Answers0