auto_enums icon indicating copy to clipboard operation
auto_enums copied to clipboard

Could it work with `Fn`/`FnMut`/`FnOnce`?

Open andersk opened this issue 8 months ago • 2 comments

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),
    }
}

andersk avatar Mar 31 '25 06:03 andersk

Please read the documentation: https://docs.rs/auto_enums/latest/auto_enums/#stdcoreops

  • Fn (requires "fn_traits" and "unstable" crate features)
  • FnMut (requires "fn_traits" and "unstable" crate features)
  • FnOnce (requires "fn_traits" and "unstable" crate features)

And example: https://docs.rs/auto_enums/latest/auto_enums/#rust-nightly

taiki-e avatar Mar 31 '25 13:03 taiki-e

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.

andersk avatar Mar 31 '25 20:03 andersk