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

Union

#[derive(Union)] generates variant accessor methods for enums: is_*(), as_*(), and to_*().

use moxy::Union;

#[derive(Union)]
enum Shape {
    Circle(f64),
    Rect { width: f64, height: f64 },
    Point,
}

This generates:

  • is_circle(), is_rect(), is_point() — boolean predicates
  • as_circle(), as_rect() — borrow variant data as Option<&T> or Option<(&T1, &T2)>
  • to_circle(), to_rect() — clone variant data as Option<T> or Option<(T1, T2)>

Unit variants only get is_*() since there is no data to access.

Attribute Helpers

Use #[moxy(variant(...))] on individual variants:

AttributeEffect
alias = "name"Rename generated methods (is_name, as_name, to_name)
skipSkip all method generation for this variant
use moxy::Union;

#[derive(Union)]
enum Token {
    #[moxy(variant(alias = "ident"))]
    Identifier(String),
    #[moxy(variant(skip))]
    Eof,
}

let t = Token::Identifier("foo".into());
assert!(t.is_ident());
assert_eq!(t.as_ident(), Some(&"foo".to_string()));

See Also