`FnOnce<...>` is not implemented for [closure]

This code doesn't work:

const N: Option<u8> = Some(0).map(|n| n + 42);

Rustc said, Playground

error[E0277]: the trait bound `[closure@src/main.rs:4:37: 4:47]: ~const FnOnce<({integer},)>` is not satisfied
    |
4   |   const N: Option<u8> = Some(0).map(|n| n + 42);
    |                                 ^^^ expected an `FnOnce<({integer},)>` closure, found `[closure@src/main.rs:4:37: 4:47]`

Although Option::map is a const fn

~const is not yet stable. Are you trying to do this on stable?

2 Likes

No, But Nightly.

So the issue is that the given closure does not implement const FnOnce, which isn't that surprising since const traits are still in the works. More generally, the fact Option::map is even const to begin with is already unstable in and of itself (const_option_ext feature), so even when using a const fn as a workaround for the closure, that feature is required.

Right now const blocks are better served by manual matches / trying to keep away from adaptors:

const N: Option<u8> = match Some(0) {
    | Some(n) => Some(n + 42),
    | None => None,
};
2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.