Rust errors / Ownership and borrowing
Rust compiler error · checked with rustc 1.99.0
Rust error E0621: explicit lifetime required in the type of `y`
What it meansThis error code indicates a mismatch between the lifetimes appearing in the function signature (i.e., the parameter types and the return type) and the data-flow found in the function body.
What rustc prints
error[E0621]: explicit lifetime required in the type of `y` --> main.rs:4:27 | 4 | if x > y { x } else { y } | ^ lifetime `'a` required | help: add explicit lifetime `'a` to the type of `y` | 1 | fn foo<'a>(x: &'a i32, y: &'a i32) -> &'a i32 { // error: explicit lifetime | ++
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
This error code indicates a mismatch between the lifetimes appearing in the function signature (i.e., the parameter types and the return type) and the data-flow found in the function body.
Erroneous code example:
fn foo<'a>(x: &'a i32, y: &i32) -> &'a i32 { // error: explicit lifetime
// required in the type of
// `y`
if x > y { x } else { y }
}
In the code above, the function is returning data borrowed from either x or y, but the 'a annotation indicates that it is returning data only from x. To fix the error, the signature and the body must be made to match. Typically, this is done by updating the function signature. So, in this case, we change the type of y to &'a i32, like so:
fn foo<'a>(x: &'a i32, y: &'a i32) -> &'a i32 {
if x > y { x } else { y }
}
Now the signature indicates that the function data borrowed from either x or y. Alternatively, you could change the body to not return data from y:
fn foo<'a>(x: &'a i32, y: &i32) -> &'a i32 {
x
}From rustc --explain E0621 (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
- E0596cannot borrow as mutable, as it is not declared as mutable
- E0597does not live long enough
- E0623lifetime mismatch
- E0626This error occurs because a borrow in a movable coroutine persists across a yield point
Up next
Often hit nextE0382: borrow of moved valueA related error from the same family.Read it next →Did this answer your question?