Skip to content

Could it work with Fn/FnMut/FnOnce? #165

@andersk

Description

@andersk

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions