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

Add `#[strum(transparent)]` argument #258

Open bobozaur opened 1 year ago

bobozaur commented 1 year ago

This crate is amazing for tackling a lot of boilerplate code and also ensuring variant name changes propagate to the trait implementations. I use AsRefStr and EnumString quite a lot.

However, a lot of times I've found myself in the situation of having something like this:

enum MyEnum {
    A,
    B,
    C,
    Other(String)
}

Afaik there's no way of propagating the AsRef<str> or FromStr implementations to the underlying String. What do you think about implementing a transparent argument to the attribute, similar to #[serde(transparent)] - only for one field provided in an unnamed/named fashion.

So then we could do:

#[derive(AsRefStr, EnumStr)]
enum MyEnum {
    A,
    B,
    C,
    #[strum(transparent)]
    Other(String)
}

I could try and pick this up if you like the idea. I think it would be handy for a lot of people.

srid commented 1 year ago

This would be good to have, without which I have no choice but to write out the instances by hand:

pub enum System {
    Aarch64Linux,
    X86_64Linux,
    X86_64Darwin,
    Aarch64Darwin,
    Other(String),
}

impl From<&str> for System {
    fn from(s: &str) -> Self {
        match s {
            "aarch64-linux" => Self::Aarch64Linux,
            "x86_64-linux" => Self::X86_64Linux,
            "x86_64-darwin" => Self::X86_64Darwin,
            "aarch64-darwin" => Self::Aarch64Darwin,
            _ => Self::Other(s.to_string()),
        }
    }
}

impl From<System> for String {
    fn from(s: System) -> Self {
        match s {
            System::Aarch64Linux => "aarch64-linux".to_string(),
            System::X86_64Linux => "x86_64-linux".to_string(),
            System::X86_64Darwin => "x86_64-darwin".to_string(),
            System::Aarch64Darwin => "aarch64-darwin".to_string(),
            System::Other(s) => s,
        }
    }
}
bobozaur commented 11 months ago

Was hoping to get some feedback from a maintainer, but I really think this would be a useful feature so I might have a shot at it after the holidays.

Thanks for the encouragement @srid !

divagant-martian commented 7 months ago

@bobozaur seems to not be documented, but from checking the code using #[strum(default)] on your variant works

bobozaur commented 3 months ago

@divagant-martian While similar in some cases, this is not the same thing. The default attribute is a catch all for EnumString but does not, for instance, delegate to the wrapped variant for AsRefStr.