lotsoftools

Understanding Rust Error E0637

Introduction to Rust Error E0637

Rust Error E0637 occurs when the reserved '_ lifetime name or &T without an explicit lifetime name is used in an illegal place. In this article, we'll discuss why this error occurs and how to fix it.

Erroneous Code Example

#![allow(unused)]
fn main() {
fn underscore_lifetime<'_>(str1: &'_ str, str2: &'_ str) -> &'_ str {
                     //^^ `'_` is a reserved lifetime name
    if str1.len() > str2.len() {
        str1
    } else {
        str2
    }
}

fn and_without_explicit_lifetime<T>()
where
    T: Into<&u32>,
          //^ `&` without an explicit lifetime name
{
}
}

Understanding the Error

First, the '_ lifetime name cannot be used as an identifier in some places because it is reserved for the anonymous lifetime. Second, using &T without an explicit lifetime name is also not allowed in some places. This results in Rust Error E0637.

Fixing the Error

To fix Rust Error E0637, use a lowercase letter as a lifetime name such as 'a, or a series of lowercase letters like 'foo. This avoids the use of the reserved '_ lifetime name or &T without an explicit lifetime.

Corrected Code Example

#![allow(unused)]
fn main() {
fn underscore_lifetime<'a>(str1: &'a str, str2: &'a str) -> &'a str {
    if str1.len() > str2.len() {
        str1
    } else {
        str2
    }
}

fn and_without_explicit_lifetime<'foo, T>()
where
    T: Into<&'foo u32>,
{
}
}

Conclusion

By using appropriate lifetime names, you can avoid Rust Error E0637 and ensure correctly functioning code. If you need further information on lifetime identifiers, refer to the Rust Book. For more information on using the anonymous lifetime in Rust 2018, see the Rust 2018 blog post.