auto_enums
auto_enums copied to clipboard
Could it work with `Fn`/`FnMut`/`FnOnce`?
Example:
use auto_enums::auto_enum;
#[auto_enum(Fn)]
fn make_operation(name: &str, operand: f64) -> impl Fn(f64) -> f64 {
match name {
"add" => move |x| x + operand,
"sub" => move |x| x - operand,
"mul" => move |x| x * operand,
"div" => move |x| x / operand,
_ => panic!("unknown operator {name}"),
}
}
This currently fails with
error: cannot find derive macro `Fn` in this scope
--> src/main.rs:3:13
|
3 | #[auto_enum(Fn)]
| ^^
|
= note: `Fn` is in scope, but it is only a trait, without a derive macro
But it could be compiled to something along these lines:
fn make_operation(name: &str, operand: f64) -> impl Fn(f64) -> f64 {
enum __Enum<__Variant0, __Variant1, __Variant2, __Variant3> {
__Variant0(__Variant0),
__Variant1(__Variant1),
__Variant2(__Variant2),
__Variant3(__Variant3),
}
let __enum = match name {
"add" => __Enum::__Variant0(move |x| x + operand),
"sub" => __Enum::__Variant1(move |x| x - operand),
"mul" => __Enum::__Variant2(move |x| x * operand),
"div" => __Enum::__Variant3(move |x| x / operand),
_ => panic!("unknown operator {name}"),
};
move |__arg0| match __enum {
__Enum::__Variant0(__fn) => __fn(__arg0),
__Enum::__Variant1(__fn) => __fn(__arg0),
__Enum::__Variant2(__fn) => __fn(__arg0),
__Enum::__Variant3(__fn) => __fn(__arg0),
}
}
Please read the documentation: https://docs.rs/auto_enums/latest/auto_enums/#stdcoreops
And example: https://docs.rs/auto_enums/latest/auto_enums/#rust-nightly
Ah indeed, I hadn’t been looking for this in the “Rust Nightly” section of the documentation. My proposed compilation wouldn’t need nightly features, though.