Kinded crate released

GitHub Repository: GitHub - greyblake/kinded: Generate Rust enum kind types without boilerplate.
Blog Post: Handling Rust enum variants with kinded crate | Serhii Potapov (greyblake)

Over the past weekend, I've developed a compact macro crate called "kinded" which, in essence, generates a new copyable enum (referred to as a "kind" enum) based on a given enum. This new enum retains the same variants as the original, but without any associated data.

For instance, consider the following code snippet:

use kinded::Kinded;

#[derive(Kinded)]
enum Beverage {
    Mate,
    Coffee(String),
}

The macro generates the following output:

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum BeverageKind {
    Mate,
    Coffee,
}
1 Like

Nice!

I'm not sure it's super idiomatic to emit other items from a derive macro, especially if there's not even a trait impl derived. A regular macro or attribute macro could be used instead. I'd love to hear others' opinions on this, as I have a similar situation in one of my projects.

2 Likes

A derive macro always leaves the original intact. Other macro types can change or even remove the original.

1 Like

I see what you mean.
With nutype I do use regular proc macro.

However, here when we write #[derive(Kinded)] it actually implements Kinded trait for Beverage, e.g.:

impl Kinded for Beverage {
    type Kind = BeverageKind;

    fn kind(&self) -> BeverageKind {
        match self {
            Beverage::Mate => BeverageKind::Mate,
            Beverage::Coffee(_) => BeverageKind::Coffee,
        }
    }
}

This is essentially the same as the already-existing EnumDiscriminants derive macro in the widely-used strum crate.

3 Likes

Thanks for bringing this.
I know about enum-kinds, but I did not know that strum can solve this problem too.
Quesiton: does strum provide any kind of traits with an associated discriminant type?

My original need for this trait was too have a trait, so I can build abstract function on top of it.
This is an example where I use it: https://github.com/greyblake/nutype/blob/master/nutype_macros/src/common/validate.rs#L24-L33

I don't think there's a separate trait, but it does impl From<&TheEnum> for TheEnumDiscriminant.

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.