Skip to main content

EnumVo

Derive Macro EnumVo 

Source
#[derive(EnumVo)]
{
    // Attributes available to this derive:
    #[vo]
}
Expand description

Derives EnumVo, Display, and FromStr for a fieldless enum.

EnumVo::variants(), Display, and FromStr are all generated from the same variant list, so they can’t drift out of sync with each other or with the enum’s actual variants. Every variant must be a unit variant (no fields) - a variant carrying data isn’t a simple enumeration, so the derive rejects it at compile time instead of silently ignoring the payload.

validate is rejected here: FromStr already exhaustively checks variant membership, so there is no “invalid but parseable” value left for a validator to catch. zeroize is rejected for the same reason as on ValueObject - a fieldless enum owns nothing worth scrubbing.

§Attributes

  • no_display - see derive_value_object.
  • rename_all = "..." - renames every variant for Display/FromStr according to one of: PascalCase (the default - unchanged), snake_case, SCREAMING_SNAKE_CASE, kebab-case, lowercase, UPPERCASE, or camelCase. An unrecognized rule name is rejected at compile time, listing the valid options.

With this crate’s own serde Cargo feature enabled (and the calling crate depending on serde directly), this also derives Serialize and Deserialize, both using the same variant/string table Display/FromStr are generated from - so serializing writes the Display string and deserializing accepts exactly what FromStr accepts, rename_all included.

§Examples

use ddd_toolkit_core::domain::EnumVo;
use ddd_toolkit_macro::EnumVo as DeriveEnumVo;
use std::str::FromStr;

#[derive(Debug, Clone, Copy, PartialEq, DeriveEnumVo)]
enum Status {
    Active,
    Inactive,
}

assert_eq!(Status::variants(), &[Status::Active, Status::Inactive]);
assert_eq!(Status::Active.to_string(), "Active");
assert_eq!(Status::from_str("Active"), Ok(Status::Active));
assert!(Status::from_str("bogus").is_err());

With rename_all, Display and FromStr agree on the renamed form:

use ddd_toolkit_macro::EnumVo as DeriveEnumVo;
use std::str::FromStr;

#[derive(Debug, Clone, Copy, PartialEq, DeriveEnumVo)]
#[vo(rename_all = "snake_case")]
enum HttpMethod {
    Get,
    PostRequest,
}

assert_eq!(HttpMethod::PostRequest.to_string(), "post_request");
assert_eq!(HttpMethod::from_str("post_request"), Ok(HttpMethod::PostRequest));
assert!(HttpMethod::from_str("PostRequest").is_err());