Auto reborrow not working for generic arguments

โš“ Rust    ๐Ÿ“… 2025-12-03    ๐Ÿ‘ค surdeus    ๐Ÿ‘๏ธ 2      

surdeus

Hi!

As far as I understand, for regular functions that takes shared references the compiler will automatically reborrow if the user instead pass in a unique reference.

let a = &mut 3;
foo(a); // <-- `a` is auto reborrowed
fn foo(_x: &u32){}

But this does not seem to work for generics

pub trait TaskArg {
    /// This should always be same as `Self`
    type T;
    fn to(self) -> Self::T;
}

impl<T> TaskArg for T {
    type T = T;
    fn to(self) -> T {
        self
    }
}

fn main() {
    let a = &mut 23; // error
    // let a = &23; // works

    expects_immutable(a);
}

fn expects_immutable<'a>(_: impl TaskArg<T = &'a u32>) {}
Compiling playground v0.0.1 (/playground)
error[E0271]: type mismatch resolving `<&mut {integer} as TaskArg>::T == &u32`
  --> src/main.rs:19:23
   |
19 |     expects_immutable(a);
   |     ----------------- ^ type mismatch resolving `<&mut {integer} as TaskArg>::T == &u32`
   |     |
   |     required by a bound introduced by this call
   |
note: expected this to be `&u32`
  --> src/main.rs:9:14
   |
 9 |     type T = T;
   |              ^
   = note:      expected reference `&u32`
           found mutable reference `&mut {integer}`
note: required by a bound in `expects_immutable`
  --> src/main.rs:22:42
   |
22 | fn expects_immutable<'a>(_: impl TaskArg<T = &'a u32>) {}
   |                                          ^^^^^^^^^^^ required by this bound in `expects_immutable`

For more information about this error, try `rustc --explain E0271`.
error: could not compile `playground` (bin "playground") due to 1 previous error

playground

I stumbled upon this here Spawn local without attribute by usbalbin ยท Pull Request #1116 ยท rtic-rs/rtic ยท GitHub

Is this just a missing, yet to be implemented, feature? Or is there a reason this can not work?

2 posts - 2 participants

Read full topic

๐Ÿท๏ธ Rust_feed