Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Common Fields

When all named variants of an enum share a field with the same name and type, Union auto-generates a shared accessor that dispatches via match.

use moxy::Union;

#[derive(Union)]
enum Animal {
    Dog { name: String, breed: String },
    Cat { name: String, color: String },
    Bird { name: String, wingspan: f64 },
}

let dog = Animal::Dog { name: "Rex".into(), breed: "Lab".into() };
let cat = Animal::Cat { name: "Whiskers".into(), color: "orange".into() };

assert_eq!(dog.name(), "Rex");
assert_eq!(cat.name(), "Whiskers");

The generated method returns a reference:

// generated:
impl Animal {
    pub fn name(&self) -> &String {
        match self {
            Self::Dog { name, .. } => name,
            Self::Cat { name, .. } => name,
            Self::Bird { name, .. } => name,
        }
    }
}

Rules

  • Only named variants participate — tuple and unit variants are ignored
  • The field must have the same name and the same type in every named variant
  • Variants with #[moxy(variant(skip))] are excluded from detection
  • Common field accessors are generated alongside the per-variant is_*/as_*/to_* methods
  • At least two named variants are required for common field detection