Why does precise capture in a trait method require capturing Self?

⚓ Rust    📅 2026-04-03    👤 surdeus    👁️ 5      

surdeus

Why do precise capture lists force you to include Self for a trait? In this example the code doesn't compile because DF is deduced to need to be 'static:

trait DoFoo {
    fn do_foo<'a, 'df>(&'df self, n: &'a i32) -> impl use<'a, Self> + Sized;
}

fn use_do_foo<DF: DoFoo>(df: &DF, n: &'static i32) {
    check_static(&df.do_foo(n));
}

fn check_static<T: 'static>(t: &T) {}
error[E0310]: the parameter type `DF` may not live long enough
 --> src/lib.rs:8:5
  |
8 |     check_static(&df.do_foo(n));
  |     ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |     |
  |     the parameter type `DF` must be valid for the static lifetime...
  |     ...so that the type `DF` will meet its required lifetime bounds

That makes sense because of the use<'a, Self>. But I don't want the Self there; the compiler forces me to add it:

error: `impl Trait` must mention the `Self` type of the trait in `use<...>`
 --> src/lib.rs:4:50
  |
3 | trait DoFoo {
  | ----------- `Self` type parameter is implicitly captured by this `impl Trait`
4 |     fn do_foo<'a, 'df>(&'df self, n: &'a i32) -> impl use<'a> + Sized;
  |                                                  ^^^^^^^^^^^^^^^^^^^^
  |
  = note: currently, all type parameters are required to be mentioned in the precise captures list

Is there a way for a trait method to return impl Trait with an associated lifetime without incorporating Self's lifetime into it?

2 posts - 2 participants

Read full topic

🏷️ Rust_feed