Skip to content

NLL: Unhelpful error message for borrowing non-static values in a 'static closure #49712

Closed
@GyrosOfWar

Description

@GyrosOfWar

The error that is shown when borrowing a value inside a closure that doesn't outlive the closure (when the closure has a 'static bound) seems misleading and less helpful than the old one. (especially since the hint to make it a move closure is missing)

Code snippet:

use std::sync::atomic::{AtomicUsize, Ordering};

fn takes_closure<F>(_closure: F)
where
    F: Fn(usize) + Sync + Send + 'static,
{

}

fn main() {
    let count = AtomicUsize::new(0);
    takes_closure(|n| {
        count.fetch_add(n, Ordering::SeqCst);
    });
}

Error without NLL:

error[E0373]: closure may outlive the current function, but it borrows `count`, which is owned by the current function
  --> src/main.rs:14:19
   |
14 |     takes_closure(|n| {
   |                   ^^^ may outlive borrowed value `count`
15 |         count.fetch_add(n, Ordering::SeqCst);
   |         ----- `count` is borrowed here
help: to force the closure to take ownership of `count` (and any other referenced variables), use the `move` keyword
   |
14 |     takes_closure(move |n| {
   |                   ^^^^^^^^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0373`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.

Error with NLL:

error[E0597]: `count` does not live long enough
  --> src/main.rs:14:19
   |
14 |       takes_closure(|n| {
   |  ___________________^
15 | |         count.fetch_add(n, Ordering::SeqCst);
16 | |     });
   | |_____^ borrowed value does not live long enough
17 |   }
   |   - borrowed value only lives until here
   |
   = note: borrowed value must be valid for the static lifetime...

error: aborting due to previous error

For more information about this error, try `rustc --explain E0597`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-NLLArea: Non-lexical lifetimes (NLL)C-enhancementCategory: An issue proposing an enhancement or a PR with one.NLL-diagnosticsWorking towards the "diagnostic parity" goalT-langRelevant to the language team

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions