Rust errors / Ownership and borrowing
Rust compiler error · checked with rustc 1.99.0
Rust error E0310: the parameter type may not live long enough
What it meansA generic type T is stored somewhere that must live for a lifetime (often 'static, as in Box<dyn Trait> or a spawned thread), but T could contain short-lived references.
What rustc prints
error[E0310]: the parameter type `T` may not live long enough --> main.rs:4:10 | 4 | foo: &'static T | ^^^^^^^^^^ | | | the parameter type `T` must be valid for the static lifetime... | ...so that the reference type `&'static T` does not outlive the data it points at | help: consider adding an explicit lifetime bound | 3 | struct Foo<T: 'static> { | +++++++++
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.
Why it happens
- Boxing a generic into
Box<dyn Any>orBox<dyn Trait>(which means+ 'static). - Sending a generic value into
thread::spawnortokio::spawn.
How to fix it
1. Add the bound the compiler suggests
fn store<T: Send + 'static>(v: T) -> Box<dyn std::any::Any + Send> {
Box::new(v)
}2. Or allow a shorter lifetime
fn wrap<'a, T: Trait + 'a>(v: T) -> Box<dyn Trait + 'a> { Box::new(v) }Other wordings of this error
the parameter type may not live long enough, so that the type will meet its required lifetime bounds, consider adding an explicit lifetime bound `T: 'static`
The compiler team's explanation
A parameter type is missing a lifetime constraint or has a lifetime that does not live long enough.
Erroneous code example:
// This won't compile because T is not constrained to the static lifetime
// the reference needs
struct Foo<T> {
foo: &'static T
}
Type parameters in type definitions have lifetimes associated with them that represent how long the data stored within them is guaranteed to live. This lifetime must be as long as the data needs to be alive, and missing the constraint that denotes this will cause this error.
This will compile, because it has the constraint on the type parameter:
struct Foo<T: 'static> {
foo: &'static T
}From rustc --explain E0310 (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
- E0262invalid lifetime parameter name: `'static`
- E0309the parameter type `T` may not live long enough
- E0311the parameter type `T` may not live long enough
- E0316nested quantification of lifetimes
Up next
Often hit nextE0382: borrow of moved valueA related error from the same family.Read it next →Did this answer your question?