Skip to main content

DefaultInstance

Trait DefaultInstance 

Source
pub trait DefaultInstance: Default + 'static {
    // Required method
    fn default_instance() -> &'static Self;
}
Expand description

Provides access to a lazily-initialized, immutable default instance of a type.

Types that implement this trait can be used as the target of MessageField<T> dereferences when the field is unset. It is also a supertrait of Message, so every generated message type must implement it.

Codegen implements this automatically for every generated message type. You only need to implement it by hand when manually implementing Message for a custom type.

The pattern codegen uses — and the recommended pattern for manual implementations — stores the instance in a static once_cell::race::OnceBox (re-exported as ::buffa::__private::OnceBox), which works in both no_std + alloc and std environments:

impl DefaultInstance for MyMessage {
    fn default_instance() -> &'static Self {
        static VALUE: ::buffa::__private::OnceBox<MyMessage>
            = ::buffa::__private::OnceBox::new();
        VALUE.get_or_init(|| ::alloc::boxed::Box::new(MyMessage::default()))
    }
}

In std-only environments std::sync::OnceLock is also available and avoids the alloc::boxed::Box wrapping:

impl DefaultInstance for MyMessage {
    fn default_instance() -> &'static Self {
        static VALUE: std::sync::OnceLock<MyMessage> = std::sync::OnceLock::new();
        VALUE.get_or_init(MyMessage::default)
    }
}

Required Methods§

Source

fn default_instance() -> &'static Self

Return a reference to the single default instance of this type.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§