enum-fields

Crates.ioenum-fields
lib.rsenum-fields
version0.1.0
sourcesrc
created_at2023-05-18 13:59:23.025293
updated_at2023-05-18 13:59:23.025293
descriptionQuickly access shared enum fields in Rust.
homepagehttps://github.com/usadson/enum-fields
repositoryhttps://github.com/usadson/enum-fields
max_upload_size
id867985
size26,341
Tristan Gerritsen (usadson)

documentation

https://docs.rs/enum-fields

README

enum-fields

Build Status Latest Version

Quickly access shared enum fields in Rust.

Installation

Add the enum-fields crate to your Cargo.toml file:

[dependencies]
enum-fields = "*"

Let your enum derive from enum_fields::EnumFields like this:

#[derive(enum_fields::EnumFields)]
pub enum MyEnum {
    ...
}

Usage

The following example showcases an enum Entity, which contains two variants: Company and Person.

/// An entity that can be either a `Company` or a `Person`.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, enum_fields::EnumFields)]
pub enum Entity {
    Company {
        name: String,
        ceo: String,
    },

    Person {
        name: String,
    }
}

Since Entity derives from [enum_fields::EnumFields], it now contains two field accessor functions (getters): Entity::name() and Entity::ceo().

let company = Entity::Company {
    name: "Apple".into(),
    ceo: "Tim Cook".into()
};

let person = Entity::Person {
    name: "Tim Berners-Lee".into()
};

println!("Company with CEO: {} named: {}",
    company.ceo().unwrap(),
    company.name()
);

println!("Person named: {}", person.name());

Note that both Company and Person have a field named name. This enforces enum-fields to let Entity::name() return the type directly.

// Since [`Entity`] has two variants that both have the `name` field,
// `Entity::name(&self)` returns the `&String`.
assert_eq!(company.name(), "Apple");
assert_eq!(person.name(), "Tim Berners-Lee");

However, only Company has field ceo, which therefore makes Entity::ceo() return an optional getter: Option<&String>.

// Only `Company` has field `ceo`, so it returns an `Option<&String>`,
// since a `Person` returns [`None`].
assert_eq!(company.ceo(), Some(&"Tim Cook".into()));
assert_eq!(person.ceo(), None);

License

Licensed under either Apache License, Version 2.0 or MIT license at your option.


Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in EnumFields by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Commit count: 8

cargo fmt