Derive Macro bagel::Constdef

source · []
#[derive(Constdef)]
Expand description

The Constdef macro

Overcome the limits of the Default trait to get constant, compile-time default implementations.

The Constdef derive macro enables you to create constant, compile-time Default implementations, in the simplest possible way. With restrictions imposed by RFC 911 on const functions, trait methods cannot currently be called in const contexts. To work around this, this crate provides you with the Constdef macro that peeks into the AST and substitutes the default value at compile-time. This enables you to call the default function in constant contexts.

Example

use bagel::Constdef;

type MyType = u16;
#[derive(Constdef)]
pub struct SpookyFriend {
    name: String,
    email: String,
    friend_names: Vec<String>,
    userid: u64,
    my_tag: MyType,
}

const SPOOKY: SpookyFriend = SpookyFriend::default();

#[test]
fn test_struct_with_heap_fields() {
    // spooky name; it's empty!
    assert_eq!(SPOOKY.name, "");
    // spooky email; it's empty!
    assert_eq!(SPOOKY.email, "");
    // spooky friend has no friends!
    assert!(SPOOKY.friend_names.is_empty());
    // spooky userid; it's 0!
    assert_eq!(SPOOKY.userid, 0);
    // spooky tag; it's 0!
    assert_eq!(SPOOKY.mytag, 0);
}

Even more complex types are supported. See crate level docs for more information.