Peternator7 / strum

A small rust library for adding custom derives to enums
https://crates.io/crates/strum
MIT License
1.8k stars 152 forks source link

Implement `get_int`/`get_bool` for properties #391

Open marxin opened 1 week ago

marxin commented 1 week ago

Fixes: #313

I am also suggesting to use i64 as return type for get_int in order to cover also negative numbers.

pali6 commented 1 week ago

It might be a good idea to instead make it so each property carries its own type based on the syntax used to declare it (e.g. int properties declared as foo = 42 as opposed to foo = "42"). That way there could be compile-time checks and there would be lesser risk of typos or of calling get_int on a string property.

Peternator7 commented 2 days ago

Hey @marxin, thanks for the PR! This has been requested for quite a while. I tend to agree with @pali6 though that this would probably be better if accepted literals of the expected type rather than parsing the string.

In some ideal world, we could accept an expression #[strum(props(my_prop = true || false))] but that's difficult because we'd need to figure out the type. I think a better solution in the first version is to change the grammar so that Prop parses a Lit rather than a LitStr then we can do a pattern match in the macro to figure out what type of property we're looking at.

marxin commented 1 day ago

Here we go. I've implemented the suggested approach for the two functions. Eventually, I decided to track the 3 categories using HashMap in enum_properties_inner, but using arrays (the original commit in this PR) might be possible. Which approach do you prefer?