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

unionize!

The unionize! macro generates a union-type enum with single-field tuple variants, variant accessor methods, and From impls — all in one invocation.

Syntax

moxy::unionize! {{
    VariantName => Type,
    ...
} as [visibility] EnumName}

Example

moxy::unionize! {{
    Text => String,
    Number => i32,
    Flag => bool,
} as pub Value}

This generates:

pub enum Value {
    Text(String),
    Number(i32),
    Flag(bool),
}

impl Value {
    pub fn is_text(&self) -> bool { ... }
    pub fn as_text(&self) -> Option<&String> { ... }
    pub fn to_text(&self) -> Option<String> { ... }

    pub fn is_number(&self) -> bool { ... }
    pub fn as_number(&self) -> Option<&i32> { ... }
    pub fn to_number(&self) -> Option<i32> { ... }

    pub fn is_flag(&self) -> bool { ... }
    pub fn as_flag(&self) -> Option<&bool> { ... }
    pub fn to_flag(&self) -> Option<bool> { ... }
}

impl From<String> for Value { ... }
impl From<i32> for Value { ... }
impl From<bool> for Value { ... }

From Impls

Each variant type gets a From implementation, enabling direct conversion:

moxy::unionize! {{
    Text => String,
    Num => i32,
} as Value}

let v: Value = "hello".to_string().into();
assert!(v.is_text());

let v: Value = 42.into();
assert!(v.is_num());

Visibility

The enum visibility is controlled by the keyword before the name:

moxy::unionize! {{ A => i32 } as pub MyType}       // pub
moxy::unionize! {{ A => i32 } as pub(crate) MyType} // pub(crate)
moxy::unionize! {{ A => i32 } as MyType}            // private