Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Struct getters #3

Open
alekratz opened this issue Jul 20, 2017 · 3 comments
Open

Struct getters #3

alekratz opened this issue Jul 20, 2017 · 3 comments

Comments

@alekratz
Copy link
Owner

For example,

#[derive(EnumGetters)]
enum MyEnum {
    Foo { bar: i32, baz: String },
}

currently does not create an implementation.

My solution would be to implement a getter for each item.

fn main() {
    let mine = MyEnum::Foo { bar: 42, baz: "In the clearing stands a boxer".to_string() };
    // Items are named after the enum, and then their name in snake_case
    println!("bar is: {}", mine.foo_bar());
    println!("baz is: {}", mine.foo_baz());
}

My only concern is that this can get wordy when using snake_case.

If you think you have something more ergonomic (or overall better!) please suggest it here.

@alekratz
Copy link
Owner Author

What about this example:

#[derive(EnumGetters)]
enum MyEnum {
    Foo { bar: i32 },
    FooBar(String),
}

With the given model, this would attempt to generate foo_bar for both variants, with #1 and #2 being implemented.

@alekratz
Copy link
Owner Author

I slept on this and I thought of another solution, which would be to generate a new struct for each struct variant. For example,

#[derive(EnumGetters)]
enum MyEnum {
    Foo { bar: i32, baz: String },
    // ... the rest
}

would generate a new struct:

struct MyEnumFoo {
    bar: i32,
    baz: String,
}

and have that be the return type of foo():

fn main() {
    let mine = MyEnum::Foo { bar: 42, baz: "In the clearing stands a boxer".to_string() };
    let foo = mine.foo();
    println!("bar is: {}", &foo.bar);
    println!("baz is: {}", &foo.baz);
}

The upsides:

  • Solves this problem
  • Gives us a natural foo.bar struct access.

The downsides:

  • How do we generate unique struct names that still produce useful error messages?
    • e.g. I don't want to have MyEnumFoo_2Pr8iigLwXYxJL4ScUHs because getting an error message
      with that would be weird and confusing.
  • Bloaty code - not sure how much of a footprint having an individual struct definition for each struct variant would have on the final binary

@alekratz alekratz added this to the v0.1.0 milestone Jul 22, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants
@alekratz and others