strum/
additional_attributes.rs

1//! # Documentation for Additional Attributes
2//!
3//! Strum supports several custom attributes to modify the generated code. At the enum level, the
4//! `#[strum(serialize_all = "snake_case")]` attribute can be used to change the case used when
5//! serializing to and deserializing from strings:
6//!
7//! ```rust
8//! use std::string::ToString;
9//! use strum;
10//! use strum_macros;
11//!
12//! #[derive(Debug, Eq, PartialEq, strum_macros::ToString)]
13//! #[strum(serialize_all = "snake_case")]
14//! enum Brightness {
15//!     DarkBlack,
16//!     Dim {
17//!         glow: usize,
18//!     },
19//!     #[strum(serialize = "bright")]
20//!     BrightWhite,
21//! }
22//!
23//! assert_eq!(
24//!     String::from("dark_black"),
25//!     Brightness::DarkBlack.to_string().as_ref()
26//! );
27//! assert_eq!(
28//!     String::from("dim"),
29//!     Brightness::Dim { glow: 0 }.to_string().as_ref()
30//! );
31//! assert_eq!(
32//!     String::from("bright"),
33//!     Brightness::BrightWhite.to_string().as_ref()
34//! );
35//! ```
36//!
37//! Custom attributes are applied to a variant by adding `#[strum(parameter="value")]` to the variant.
38//!
39//! - `serialize="..."`: Changes the text that `FromStr()` looks for when parsing a string. This attribute can
40//!    be applied multiple times to an element and the enum variant will be parsed if any of them match.
41//!
42//! - `to_string="..."`: Similar to `serialize`. This value will be included when using `FromStr()`. More importantly,
43//!    this specifies what text to use when calling `variant.to_string()` with the `ToString` derivation, or when calling `variant.as_ref()` with `AsRefStr`.
44//!
45//! - `default`: Applied to a single variant of an enum. The variant must be a Tuple-like
46//!    variant with a single piece of data that can be create from a `&str` i.e. `T: From<&str>`.
47//!    The generated code will now return the variant with the input string captured as shown below
48//!    instead of failing.
49//!
50//!     ```rust,ignore
51//!     // Replaces this:
52//!     _ => Err(strum::ParseError::VariantNotFound)
53//!     // With this in generated code:
54//!     default => Ok(Variant(default.into()))
55//!     ```
56//!     The plugin will fail if the data doesn't implement From<&str>. You can only have one `default`
57//!     on your enum.
58//!
59//! - `disabled`: removes variant from generated code.
60//!
61//! - `message=".."`: Adds a message to enum variant. This is used in conjunction with the `EnumMessage`
62//!    trait to associate a message with a variant. If `detailed_message` is not provided,
63//!    then `message` will also be returned when get_detailed_message() is called.
64//!
65//! - `detailed_message=".."`: Adds a more detailed message to a variant. If this value is omitted, then
66//!    `message` will be used in it's place.
67//!
68//! - `props(key="value")`: Enables associating additional information with a given variant.