Understanding Rust Error E0771: Non-'static Lifetime in Const Generic
Introduction to Rust Error E0771
The Rust Error E0771 occurs when a non-'static lifetime is used in a const generic parameter. Currently, Rust does not support const generics with non-'static lifetimes. This error typically occurs while using the 'adt_const_params' feature in Rust.
Erroneous Code Example
#![allow(unused)]
#![feature(adt_const_params)]
fn main() {
fn function_with_str<'a, const STRING: &'a str>() {}
}
In the example above, the function 'function_with_str' is declared with a non-'static lifetime 'a and const generic parameter STRING. This causes Rust to emit Error E0771.
Fixing the Error
To resolve this issue, you must change the lifetime in the const generic parameter to 'static. Here's the corrected code example:
#![allow(unused)]
#![feature(adt_const_params)]
fn main() {
fn function_with_str<const STRING: &'static str>() {}
}
In the corrected code, the lifetime is changed to 'static for the const generic parameter STRING. This change prevents Rust from emitting Error E0771.
Additional Resources
For more information regarding Rust Error E0771 and its related issues, please refer to the GitHub issue #74052.