Derive Macro bagel::Constdef

source · []
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.


use bagel::Constdef;

type MyType = u16;
pub struct SpookyFriend {
    name: String,
    email: String,
    friend_names: Vec<String>,
    userid: u64,
    my_tag: MyType,

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

fn test_struct_with_heap_fields() {
    // spooky name; it's empty!
    assert_eq!(, "");
    // spooky email; it's empty!
    assert_eq!(, "");
    // spooky friend has no friends!
    // 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.