Crates.io | convertable-errors |
lib.rs | convertable-errors |
version | 0.1.0 |
source | src |
created_at | 2021-06-23 18:06:25.764784 |
updated_at | 2021-06-23 18:06:25.764784 |
description | This crate defines an ergonomic macro for deriving From |
homepage | |
repository | https://github.com/dowlandaiello/convertable-errors |
max_upload_size | |
id | 414069 |
size | 8,791 |
This crate defines a macro for deriving From
enum ForeignType;
enum MyEnum {
Variant(ForeignType)
}
impl From<ForeignType> for MyEnum {
fn from(v: ForeignType) -> Self {
Self::Variant(v)
}
}
This is how we would typically define conversions from foreign types to enum variants that contain those foreign types. But convertable-errors provides a declarative Rust macro to generate these conversions for us. Convertable errors can be used to generate these types of conversions for any type of Rust enum (excluding enums with struct variants, for now), but my main use case is error-like enums.
Using convertable-errors, we can generate From<T>
definitions for our enum variants like so:
enum ForeignType;
convertable_error! {
enum MyEnum {
(Variant(ForeignType), [(ForeignType, Self::Variant)]
}
}
The syntax for defining a convertable enum with convertable-errors is as follows:
enum MyError { (Variant(ForeignType)), (Variant1) }
enum MyError { (Variant(ForeignType), [ ... ]), (Variant1) }
[(ForeignType, Self::Variant)]
. Internally, this second member can be a closure |x| Self::Variant(x)
, a unit variant closure |_| Self::Variant1
, or simply a variant identifier
where the value of the foreign type will be stored: Self::Variant
. In practice, you can use
this macro for any enum, but I find it most useful for Error-like enums.NOTE: This isn't a serious project, I might have made some mistakes, so feel free to open a PR :) This is just a helpful snippet that I use and felt like sharing.