serde_closure
Serializable closures.
This library provides macros to wrap closures such that they can serialized and sent between other processes running the same binary.
For example, if you have the same binary running on each of a cluster of machines, this library would help you to send closures between them.
This library aims to work in as simple and un-magical a way as possible. It
currently requires nightly Rust for the unboxed_closures and fn_traits
features (rust issue #29625).
- There are three macros, FnOnce, FnMut and Fn, corresponding to the three types of Rust closure.
- The captured variables, i.e. those variables that are referenced by the closure but are declared outside of it, must be explicitly listed.
- There are currently some minor limitations of syntax over normal closure syntax, which are documented below.
- The closure is coerced to a function pointer, which is wrapped by relative::Pointer such that it can safely be sent between processes.
Examples of wrapped closures
Inferred, non-capturing closure:
|a| a+1
FnMut!
Annotated, non-capturing closure:
|a: String|
FnMut!
Inferred closure, capturing num:
let mut num = 0;
move |a| num += a
let mut num = 0;
FnMut!
Note: If any variables are captured then the move keyword must be present. As
this is a FnMut closure, num is a mutable reference, and must be dereferenced
to use.
Capturing hello requiring extra annotation:
let mut hello = Stringnew;
move |a|
let mut hello = Stringnew;
FnMut!
Note: hello needs its type annotated in the closure.
Complex closure, capturing a and b:
let = ;
move |c, d: &_, e: &mut _, f: String, g: &String, h: &mut String|
let = ;
FnMut!
Cosmetic limitations
As visible above, there are currently some limitations that often necessitate extra annotation that you might typically expect to be redundant.
- Type inference doesn't work as well as normal, hence extra type annotations might be needed;
- The captured variables in FnMut and Fn closures are references, so need to be dereferenced;
- Types cannot be annotated in the list of captured variables;
- If any of the closure arguments are annotated with types (i.e.
|a:i32|0) then all must be (though_can be used), and patterns can no longer be used (i.e.|&a:&i32|0will not work). - The
movekeyword must be present if any variables are captured.
License
Licensed under Apache License, Version 2.0, (LICENSE.txt or http://www.apache.org/licenses/LICENSE-2.0).
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be licensed as above, without any additional terms or conditions.