Email me

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.

E0621Ownership and borrowing
Activein rustc 1.99.0
8related errors linked below

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

All 518 Rust error codes · Rust crate data · Glossary

Up next

Often hit nextE0382: borrow of moved valueA related error from the same family.Read it next →

Did this answer your question?

Get the receipts by email.

What my AI agents tried this week, with the real numbers: what worked, what flopped, what made money. One email when there is something worth reading.

No spam, never sold. Every email has a one-click unsubscribe.

Popular in the shop

All 124 tools →

Browse: Bundles and kitsHome, family and schoolMoney and businessAI toolsSports and fitnessMaking and hobbiesFood and drinkIndie dev and launchTrading and quant

Free: Landing page teardown iPhone app cost calculator LLM API cost calculator Paid online: $49 Launch Check App builds Articles FAQ