Attribute Macro binroots::binroots_enum

source ·
#[binroots_enum]
Expand description

binroots_enum

A procedural macro attribute that enables serialization, default and debug operations for an enum. Usage #[binroots_enum] can be applied to enums. The attribute generates an implementation of binroots::Serialize (re-exported from serde::Serialize), and attempts to automatically pick the default value.

use binroots::binroots_enum;

#[binroots_enum]
pub enum MyEnum {
    VariantA,
    VariantB,
    #[default]
    VariantC,
}

Notice how we’re using #[default] to mark the default variant of MyEnum. It’s also possible for #[binroots_enum] to automatically pick the default variant:

use binroots::binroots_enum;

#[binroots_enum]
pub enum MyEnum {
    None, // Automatically chosen to be the default value
          // #[binroots_enum] automatically picks the first instance of either "None", "Nothing", "Default" or "Empty" to be default.
    VariantA,
    VariantB,
}

#[binroots_enum(manual)]
pub enum MyManualEnum {
    None, // Not selected as the default variant because we use the `manual` annotation
    #[default]
    VariantA,
    VariantB
}

The generated code includes a new implementation of the input struct with the following changes: - derives [Debug], [Default], binroots::Serialize - Adds a new method to the struct, which constructs a new instance of the struct from its fields. - A #[default] marker inserted wherever possible, overrided by the manual annotation

use binroots::binroots_enum;
use binroots::save::{RootType, Save};

#[binroots_enum]
pub enum Activity {
    Nothing,
    Playing(String),
    Watching(String),
}

fn main() {
    let activity = Activity::Playing("bideo games".into());

    activity.save("activity", RootType::InMemory).unwrap(); // Saves the enum to the disk
}