12

I'm trying to do some higher order programming in Rust, but I'm having some difficulty dealing with closures. Here's a code snippet that illustrates one of the problems I'm having:

pub enum Foo {
    Bar(Box<FnOnce(i32)>),
}

pub fn app(i: i32, arg: Foo) {
    match arg {
        Foo::Bar(f) => f(i),
    }
}

When I compile this piece of code I get the following error message:

error[E0161]: cannot move a value of type std::ops::FnOnce(i32) + 'static: the size of std::ops::FnOnce(i32) + 'static cannot be statically determined
 --> src/main.rs:7:24
  |
7 |         Foo::Bar(f) => f(i),
  |                        ^

Since I put the function in a Box, I would have thought that that would deal with the problem of the compiler not knowing the size. How can I make the above program compile?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
svenningsson
  • 4,009
  • 1
  • 24
  • 32

2 Answers2

18

Here's the FnOnce trait's definition (simplified a little):

pub trait FnOnce<Args> {
    type Output;

    fn call_once(self, args: Args) -> Self::Output;
}

To call a FnOnce closure, you need to be able to move the closure value itself into the invocation. Note that self has to be the actual closure type; a Box<dyn FnOnce> is a different type altogether.

Rust 1.35

Box<dyn FnOnce> is now able to be called; your original code works as-is.

Prior versions

There is a type in the standard library for working around this situation: FnBox. Unfortunately, it's unstable.

Your alternate choices are:

  • Refactor the code so that instead of Box<FnOnce>, you preserve the actual closure type.
  • Use Box<FnMut> instead.
  • Wait for FnBox to stabilise.
  • Switch to a nightly compiler.
Stargateur
  • 24,473
  • 8
  • 65
  • 91
DK.
  • 55,277
  • 5
  • 189
  • 162
  • Thanks for the answer.Using the actual closure type is not an option for me since I need to be able to store different closures in the enum. I don't know how to make the `Box` suggestion work, I get an error when I try that. What I've managed to do instead is to just say `Box`. That helped me compile the example above. However, I cannot create an enum using that type since it doesn't match the type of the closure. So I guess I'm left with trying a nightly compiler. – svenningsson May 23 '15 at 10:53
  • @svenningsson: Use `Box` instead; because `FnMut` is "object safe", you *can* call one through a `Box` (or any indirection, really). The only thing you can't do is have the closure consume values (though you can work around that with `Option`). – DK. May 23 '15 at 10:55
  • The error I get when I try `Box` is the following: cannot borrow immutable `Box` content `*f` as mutable src/lib.rs:36 Foo::Bar(f) => f(i) – svenningsson May 23 '15 at 10:58
  • 1
    @svenningsson: A `FnMut` needs to be able to mutate the closure value when called, so use `Foo::Bar(mut f) => f(i)` instead to make the `f` binding mutable. – DK. May 23 '15 at 11:29
  • Ok thanks. That makes my example compile. Unfortunately, using `FnMut` prevents me from creating the kind of closures I like, but that's a different problem and maybe I can find a way around that. – svenningsson May 23 '15 at 13:47
  • Just want to confirm that `FnBox` solves my problem. Thanks again! – svenningsson May 23 '15 at 15:37
  • There's another choice: Just copy the `FnBox` implementation. This is what crossbeam does, and it's pretty simple - just a few lines - since they only need a specific function, which might be ok for you too. See https://github.com/crossbeam-rs/crossbeam/blob/07245b3f3d2d938017581a71c02754be9e794ae8/src/lib.rs#L43 – kralyk Jul 02 '17 at 09:45
2

It is unlikely FnBox becomes stable, but for the time being you can wrap the F: FnOnce(...) -> ... in an Option<F>, bind it in a mutable closure and unwrap and call it inside (so it panics if it gets called more than once); the resulting closure can be boxed as Box<FnMut(...) -> ...>, which you might want to wrap somehow to make sure it only gets used ("called") once.

See (my) boxfnonce crate.

Stefan
  • 5,304
  • 2
  • 25
  • 44