Skip to content

Function pointer does not fulfill the required lifetime #80317

@ldr709

Description

@ldr709

Function pointers have no lifetime of their own, and essentially are 'static (Unsafe Code Guidelines Reference), so I would expect fn(T) -> U: 'a to hold for any lifetime 'a and types T, U. A function pointer that lived longer than its argument type would be fine, since it won't be possible to make an instance of the argument type after it's expired, and so you cannot call it then. Similarly, there's nothing wrong with a function pointer that lives longer than its return type, as outside the return type's lifetime you either won't be able to call it or it will never return.

Yet the following example fails to compile.

pub fn foo<'a, T: 'a>() {}

pub fn bar<'a, 'b>() {
    foo::<'a, fn(&'b u32)>(); // Errors
}

Playground

error[E0477]: the type `fn(&'b u32)` does not fulfill the required lifetime
 --> src/lib.rs:5:5
  |
5 |     foo::<'a, fn(&'b u32)>(|_x: &'b u32| {}); // Errors
  |     ^^^^^^^^^^^^^^^^^^^^^^
  |
note: type must outlive the lifetime `'a` as defined on the function body at 3:12
 --> src/lib.rs:3:12
  |
3 | pub fn bar<'a, 'b>() {
  |            ^^

The compiler seems to think that a function pointer is only valid for as long as the types it uses are, rather than for the duration of the program.

I have also run into a similar issue when using Box<dyn Fn(&'b u32)> (and also Box<dyn Fn(&'b u32) + 'a>) instead of fn(&'b u32), but I thought that the function pointer case would be the clearest.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lifetimesArea: Lifetimes / regionsC-bugCategory: This is a bug.T-typesRelevant to the types team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions