[Solved] Auto gen enum options as function?

  1. Consider the following code:

pub enum Foo {
    A(i32),
    B(f32, f32),
}

impl Foo {
    pub fn new_a(data: i32) -> Foo { Foo::A(data) }
    pub fn new_b(lhs: f32, rhs: f32) -> Foo { Foo::B(lhs, rhs) }
}
  1. In this code, is there a way to auto gen new_a, new_b? The idea is that every "choice" of a enum can also be viewed as a "function" which takes its args and outputs a obj of the enum type.

Not automatically, though the names of the enum variants act as exactly the functions you've written (i.e. they can be passed to map, etc, as functions). What's your use case?

1 Like

This is, for reasons of implementation, literally a function call exactly as you want, and (as noted above) can be called by path instead of a closure.

See the paragraph preceeding the last example of the section on function pointers, which I tweaked after learning about this in an earlier thread here.

1 Like

@cbiffle , @dcarosone : LOL. Problem = entirely due to my lack of knowledge about enum's -- that they ALREADY SERVE AS FUNCTIONS. :slight_smile:

There is no longer a question here, this was due 100% to me not knowing about this particular feature of Rust. :slight_smile:

5 Likes

Great! Happy to help.