How to automatically find function from enum?

i want a magic function or something that can choose a func in current scale with name in enum
i expect something like this:

enum A {
    A,
    B,
}

fn A() {
    println!("this is fn A")
}
fn B() {
    println!("this is fn B")
}

fn get_func<T: Fn(), E: std::error::Error>(e: A) -> Result<T, E> {
    todo!()
}

is it possible? hope for ur answer

In the simple case you show in your example you can return function pointers. Alternatively—for more complex cases where your enum has to match against user-defined closures that capture something (i.e. are not coercible to a function pointer)—you can use dynamic dispatch:

enum A {
    A,
    B,
}

fn a() {
    println!("this is fn A")
}
fn b() {
    println!("this is fn B")
}

fn get_func<E: std::error::Error>(e: A) -> Result<fn(), E> {
    match e {
        A::A => Ok(a),
        A::B => Ok(b),
    }
}

fn get_func_dyn<E: std::error::Error>(e: A) -> Result<Box<dyn Fn()>, E> {
    match e {
        A::A => Ok(Box::new(a)),
        A::B => Ok(Box::new(b)),
    }
}

Playground.

This has all the signs of an XY problem. It might be more useful if you specify directly the problem that you are trying to solve rather than the way you think could be solved.

Rust's runtime reflection capabilities are limited, and certainly not the go to solution for most of software design problems.

1 Like

i want in the furture i can extend this function's ability by just add enum variants to without adding new pattern in match block, in other word i want i can just write get_func() once to automatically extend the ability of this function

This sounds like it'd be achievable with a derive macro. This'd be a bit hacky though (unless you generate the functions in the macro as well) and I would prefer a simple match expression. It is easy to reason about even for larger enums and having code that is quick to read is better than code that is quick to write IMO.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.