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

Enums

The Default derive works with enums. Mark one variant with #[moxy(default)] to use it as the default.

Unit Variant

use moxy::Default;

#[derive(Default, PartialEq, Debug)]
enum Status {
    Active,
    #[moxy(default)]
    Idle,
}

assert_eq!(Status::default(), Status::Idle);

Named Variant

Fields within the default variant use the same #[moxy(default = expr)] syntax as struct fields:

use moxy::Default;

#[derive(Default)]
enum Color {
    #[moxy(default)]
    Rgb {
        #[moxy(default = 255u8)]
        r: u8,
        g: u8,
        b: u8,
    },
    Hex(String),
}

let c = Color::default();
// c == Color::Rgb { r: 255, g: 0, b: 0 }

Tuple Variant

use moxy::Default;

#[derive(Default, PartialEq, Debug)]
enum Wrapper {
    #[moxy(default)]
    Value(#[moxy(default = 42)] i32),
    Empty,
}

assert_eq!(Wrapper::default(), Wrapper::Value(42));

Rules

  • Exactly one variant must be marked with #[moxy(default)]
  • Zero or multiple marked variants produce a compile error
  • Fields without #[moxy(default = expr)] use Default::default()