Rust errors / Ownership and borrowing
Rust compiler error · checked with rustc 1.99.0
Rust error E0261: use of undeclared lifetime name `'a`
What it meansAn undeclared lifetime was used.
What rustc prints
error[E0261]: use of undeclared lifetime name `'a` --> main.rs:2:12 | 2 | fn foo(x: &'a str) { } | ^^ undeclared lifetime | help: consider introducing lifetime `'a` here | 2 | fn foo<'a>(x: &'a str) { } | ++++
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
An undeclared lifetime was used.
Erroneous code example:
// error, use of undeclared lifetime name `'a`
fn foo(x: &'a str) { }
struct Foo {
// error, use of undeclared lifetime name `'a`
x: &'a str,
}
These can be fixed by declaring lifetime parameters:
struct Foo<'a> {
x: &'a str,
}
fn foo<'a>(x: &'a str) {}
Impl blocks declare lifetime parameters separately. You need to add lifetime parameters to an impl block if you're implementing a type that has a lifetime parameter of its own. For example:
struct Foo<'a> {
x: &'a str,
}
// error, use of undeclared lifetime name `'a`
impl Foo<'a> {
fn foo<'a>(x: &'a str) {}
}
This is fixed by declaring the impl block like this:
struct Foo<'a> {
x: &'a str,
}
// correct
impl<'a> Foo<'a> {
fn foo(x: &'a str) {}
}From rustc --explain E0261 (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
- E0227ambiguous lifetime bound, explicit lifetime bound required
- E0228cannot deduce the lifetime bound for this trait object type from context
- E0262invalid lifetime parameter name: `'static`
- E0309the parameter type `T` may not live long enough
Up next
Often hit nextE0382: borrow of moved valueA related error from the same family.Read it next →Did this answer your question?