Crates.io | anon_enum |
lib.rs | anon_enum |
version | 1.1.0 |
source | src |
created_at | 2023-03-17 06:27:35.34054 |
updated_at | 2023-03-25 20:12:09.20608 |
description | Enum types with fully-generic variants |
homepage | |
repository | https://gitlab.com/Ssolar5/anon_enum |
max_upload_size | |
id | 812461 |
size | 43,115 |
Enum types with fully-generic variants.
This library defines enum types which are generic over from 2 (Enum2
) to 16 (Enum16
) type parameters.
Each type parameter of a given enum type is the type of the single field of its respective variant of the same name
(all variants are tuple structs with a single field).
use std::collections::HashMap;
use anon_enum::Enum2;
/// Error type stating that a map does not contain a given key.
struct ErrKeyNotFound;
/// Error type stating that an integer overflow occured during
/// an arithmetic operation.
struct ErrIntegerOverflow;
/// Maps a `str` to an integer of type `i32` and returns the integer plus one.
fn get_and_add_one(
map: &HashMap<&str, i32>,
key: &str,
) -> Result<i32, Enum2<ErrKeyNotFound, ErrIntegerOverflow>> {
Ok(map
.get(key)
.ok_or(Enum2::T0(ErrKeyNotFound))?
.checked_add(1)
.ok_or(Enum2::T1(ErrIntegerOverflow))?)
}
fn main() {
let mut fruit_count = HashMap::new();
fruit_count.insert("Lime", 5);
fruit_count.insert("Orange", i32::MAX);
matches!(get_and_add_one(&fruit_count, "Lime"), Ok(6));
matches!(
get_and_add_one(&fruit_count, "Tangerine"),
Err(Enum2::T0(ErrKeyNotFound))
);
matches!(
get_and_add_one(&fruit_count, "Orange"),
Err(Enum2::T1(ErrIntegerOverflow))
);
}
An enum of more than 16 variants may be expressed by setting
the generic type T15
of Enum16
to an enum type:
// Enum of 18 variants.
Enum16<T0, T1, ..., T14, Enum3<T15, T16, T17>>