Rust errors / Ownership and borrowing
Rust compiler error · checked with rustc 1.99.0
Rust error E0623: lifetime mismatch
What it meansA lifetime didn't match what was expected.
What rustc prints
error[E0623]: lifetime mismatch
--> main.rs:15:8
|
15 | x: Foo<'in_, 'out, T>,
| ^^^^^^^^^^^^^^^^^^
| |
| this parameter and the return type are declared with different lifetimes...
| ...but data from `x` is returned here
16 | sadness: &'in_ T
17 | ) -> &'out T {
| -------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
A lifetime didn't match what was expected.
Erroneous code example:
struct Foo<'a, 'b, T>(std::marker::PhantomData<(&'a (), &'b (), T)>)
where
T: Convert<'a, 'b>;
trait Convert<'a, 'b>: Sized {
fn cast(&'a self) -> &'b Self;
}
impl<'long: 'short, 'short, T> Convert<'long, 'short> for T {
fn cast(&'long self) -> &'short T {
self
}
}
// error
fn badboi<'in_, 'out, T>(
x: Foo<'in_, 'out, T>,
sadness: &'in_ T
) -> &'out T {
sadness.cast()
}
In this example, we tried to set a value with an incompatible lifetime to another one ('in_ is unrelated to 'out). We can solve this issue in two different ways:
Either we make 'in_ live at least as long as 'out:
struct Foo<'a, 'b, T>(std::marker::PhantomData<(&'a (), &'b (), T)>)
where
T: Convert<'a, 'b>;
trait Convert<'a, 'b>: Sized {
fn cast(&'a self) -> &'b Self;
}
impl<'long: 'short, 'short, T> Convert<'long, 'short> for T {
fn cast(&'long self) -> &'short T {
self
}
}
fn badboi<'in_: 'out, 'out, T>(
x: Foo<'in_, 'out, T>,
sadness: &'in_ T
) -> &'out T {
sadness.cast()
}
Or we use only one lifetime:
struct Foo<'a, 'b, T>(std::marker::PhantomData<(&'a (), &'b (), T)>)
where
T: Convert<'a, 'b>;
trait Convert<'a, 'b>: Sized {
fn cast(&'a self) -> &'b Self;
}
impl<'long: 'short, 'short, T> Convert<'long, 'short> for T {
fn cast(&'long self) -> &'short T {
self
}
}
fn badboi<'out, T>(x: Foo<'out, 'out, T>, sadness: &'out T) -> &'out T {
sadness.cast()
}From rustc --explain E0623 (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
- E0597does not live long enough
- E0621explicit lifetime required in the type of `y`
- E0626This error occurs because a borrow in a movable coroutine persists across a yield point
- E0637`'_` cannot be used here
Up next
Often hit nextE0382: borrow of moved valueA related error from the same family.Read it next →Did this answer your question?