Understanding Rust Error E0687: In-band Lifetimes in fn/Fn Syntax

Introduction to Rust Error E0687

Rust Error E0687 occurs when in-band lifetimes are used with function (fn) or trait function (Fn) syntax. In these cases, lifetimes must be explicitly declared using the <...> binders.

Erroneous Code Examples


fn foo(x: fn(&'a u32)) {} // error!

fn bar(x: &Fn(&'a u32)) {} // error!

fn baz(x: fn(&'a u32), y: &'a u32) {} // error!

struct Foo<'a> { x: &'a u32 }

impl Foo<'a> {
    fn bar(&self, x: fn(&'a u32)) {} // error!

Corrected Code Examples

fn foo<'a>(x: fn(&'a u32)) {} // ok!

fn bar<'a>(x: &Fn(&'a u32)) {} // ok!

fn baz<'a>(x: fn(&'a u32), y: &'a u32) {} // ok!

struct Foo<'a> { x: &'a u32 }

impl<'a> Foo<'a> {
    fn bar(&self, x: fn(&'a u32)) {} // ok!

In-band Lifetime and Function Syntax

In-band lifetimes were introduced in Rust to simplify indicating lifetimes within function signatures without writing them multiple times. However, using them in function and trait function syntax, as shown in the erroneous code examples above, leads to error E0687.

To fix this error, declare the lifetimes explicitly using <...> binders, as shown in the corrected code examples. By doing this, the code becomes more readable, and the error is resolved.

Key Takeaways

1. Rust Error E0687 is caused by the use of in-band lifetimes in function (fn) or trait function (Fn) syntax. 2. To fix the error, declare lifetimes explicitly using <...> binders in the function signatures. 3. In-band lifetimes can simplify function signatures, but they should not be used in function or trait function syntax.

Recommended Reading