Rust errors / Ownership and borrowing
Rust compiler error · checked with rustc 1.99.0
Rust error E0700: hidden type for `impl Trait<'y>` captures lifetime that does not appear in bounds
What it meansThe impl Trait return type captures lifetime parameters that do not appear within the impl Trait itself.
What rustc prints
error[E0700]: hidden type for `impl Trait<'y>` captures lifetime that does not appear in bounds --> main.rs:10:5 | 7 | fn foo<'x, 'y>(x: Cell<&'x u32>) -> impl Trait<'y> | -- -------------- opaque type defined here | | | hidden type `Cell<&'x u32>` captures the lifetime `'x` as defined here ... 10 | x | ^ | help: add a `use<...>` bound to explicitly capture `'x` | 7 | fn foo<'x, 'y>(x: Cell<&'x u32>) -> impl Trait<'y> + use<'y, 'x> | +++++++++++++
Real output of rustc 1.99.0 compiling the official example below (2021 edition). Your names and line numbers will differ; the first line is the part to match.
The compiler team's explanation
The impl Trait return type captures lifetime parameters that do not appear within the impl Trait itself.
Erroneous code example:
use std::cell::Cell;
trait Trait<'a> { }
impl<'a, 'b> Trait<'b> for Cell<&'a u32> { }
fn foo<'x, 'y>(x: Cell<&'x u32>) -> impl Trait<'y>
where 'x: 'y
{
x
}
Here, the function foo returns a value of type Cell<&'x u32>, which references the lifetime 'x. However, the return type is declared as impl Trait<'y> -- this indicates that foo returns "some type that implements Trait<'y>", but it also indicates that the return type **only captures data referencing the lifetime 'y**. In this case, though, we are referencing data with lifetime 'x, so this function is in error.
To fix this, you must reference the lifetime 'x from the return type. For example, changing the return type to impl Trait<'y> + 'x would work:
use std::cell::Cell;
trait Trait<'a> { }
impl<'a,'b> Trait<'b> for Cell<&'a u32> { }
fn foo<'x, 'y>(x: Cell<&'x u32>) -> impl Trait<'y> + 'x
where 'x: 'y
{
x
}From rustc --explain E0700 (1.99.0), part of the Rust project, MIT or Apache-2.0. Official page.
Related errors
- E0382borrow of moved value
- E0499cannot borrow as mutable more than once at a time
- E0502cannot borrow as mutable because it is also borrowed as immutable
- E0106missing lifetime specifier
- E0637`'_` cannot be used here
- E0657`impl Trait` cannot capture higher-ranked lifetime from outer `impl Trait`
- E0712thread-local variable borrowed past end of function
- E0713borrow may still be in use when destructor runs
Up next
Often hit nextE0382: borrow of moved valueA related error from the same family.Read it next →Did this answer your question?