Generate Rust enum kind types without boilerplate.
```rs use kinded::Kinded;
enum Drink { Mate, Coffee(String), Tea { variety: String, caffeine: bool } }
let drink = Drink::Coffee("Espresso".toowned()); asserteq!(drink.kind(), DrinkKind::Coffee); ```
Note, the definition of DrinkKind
enum was generated automatically as well as Drink::kind()
method.
The library provides Kinded
trait:
```rs pub trait Kinded { type Kind: PartialEq + Eq + Debug + Clone + Copy;
fn kind(&self) -> Self::Kind;
} ```
From the example above, the derived implementation of Kinded
for Drink
resembles the following:
```rs impl Kinded for Drink { type Kind = DrinkKind;
fn kind(&self) -> DrinkKind {
match self {
Drink::Mate => DrinkKind::Mate,
Drink::Coffee(..) => DrinkKind::Coffee,
Drink::Tea { .. } => DrinkKind::Tea,
}
}
} ```
The Kinded
trait allows to build abstract functions that can be used with different enum types.
By default the kind type name is generated by adding postfix Kind
to the original enum name.
This can be customized with kind =
attribute:
```rs use kinded::Kinded;
enum Drink { Mate, Coffee(String), Tea { variety: String, caffeine: bool } } ```
By default the kind type implements the following traits: Debug
, Clone
, Copy
, PartialEq
, Eq
, From<T>
, From<&T>
.
Extra traits can be derived with derive(..)
attribute:
```rs use kinded::Kinded; use std::collections::HashSet;
enum Drink { Mate, Coffee(String), Tea { variety: String, caffeine: bool } }
let mut drinkkinds = HashSet::new(); drinkkinds.insert(DrinkKind::Mate); ```
There is a very similar crate enum-kinds that does almost the same job.
The main difference between kinded
and enum-kinds
crate is that kinded
provides the Kinded
trait, on top of which
users can implement abstract functions and use them with different enum types.
Another minor difference is that apart from From<T>
and From<&T>
conversions, kidned
also implements kind()
function on the enum type.
Today I live in Berlin, I have the luxury to live a physically safe life. But I am Ukrainian. The first 25 years of my life I spent in Kharkiv, the second-largest city in Ukraine, 60km away from the border with russia. Today about a third of my home city is destroyed by russians. My parents, my relatives and my friends had to survive the artillery and air attack, living for over a month in basements.
Some of them have managed to evacuate to EU. Some others are trying to live "normal lifes" in Kharkiv, doing there daily duties. And some are at the front line right now, risking their lives every second to protect the rest.
I encourage you to donate to Charity foundation of Serhiy Prytula. Just pick the project you like and donate. This is one of the best-known foundations, you can watch a little documentary about it. Your contribution to the Ukrainian military force is a contribution to my calmness, so I can spend more time developing the project.
Thank you.
MIT © Serhii Potapov