DefaultBoxed

Trait DefaultBoxed 

Source
pub unsafe trait DefaultBoxed {
    // Required method
    unsafe fn default_in_place(ptr: *mut Self);

    // Provided methods
    fn default_boxed() -> Box<Self>
       where Self: Sized { ... }
    fn default_boxed_array<const N: usize>() -> Box<[Self; N]>
       where Self: Sized { ... }
}
Expand description

Helper trait to create a boxed instance of the given type with a default value for each field.

This trait can be derived for structs.

To derive this trait, each field needs to also implement this trait, but all types which implements Default implements this trait via the blanket impl already.

In addition, if a field is an array, only the item type needs to implement this trait, and each item would be initialized separately.

§Safety

Implementations must ensure that default_in_place initializes the value on the given pointer.

Required Methods§

Source

unsafe fn default_in_place(ptr: *mut Self)

Fill the given memory location with default value.

§Safety

For callers, behavior is undefined if ptr is not valid for writes, or it is not properly aligned.

For impls, behavior is undefined if this method reads from ptr.

Provided Methods§

Source

fn default_boxed() -> Box<Self>
where Self: Sized,

Create a boxed instance with default value for each field.

Source

fn default_boxed_array<const N: usize>() -> Box<[Self; N]>
where Self: Sized,

Create a boxed array of the given size with default value of the type.

use default_boxed::DefaultBoxed;
let arr = u32::default_boxed_array::<32>();
assert_eq!(arr, Box::new([0; 32]));

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§