Compiler can't use the shorter of two lifetimes when calling a function with a single generic lifetime parameter

⚓ Rust    📅 2025-09-18    👤 surdeus    👁️ 2      

surdeus

While writing a library, I stumbled across an issue, which can be reproduced by the following minimal example:

struct T;

fn foo<'a>(a : impl Iterator<Item=&'a T>, b : &'a T) {
   _ = (a, b); 
}

fn bar<'a>(a : impl Iterator<Item=&'a T>) {
    let b = T;
    // Compiler complains here that &b doesn't life long enough (requires 'a).
    foo(a, &b);
}

fn main() {
    let a = vec![T, T];
    bar(a.iter());
}

This code does not compile due to the reason stated in the comment.
But I don't understand why. My understanding would be that 'a of foo is choosen to be the shorter of the two lifetimes (lifetime of b) and should compile fine.

5 posts - 3 participants

Read full topic

🏷️ Rust_feed