Macro try_init

Source
macro_rules! try_init {
    ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? {
        $($fields:tt)*
    }? $err:ty) => { ... };
}
Expand description

Construct an in-place fallible initializer for structs.

If the initialization can complete without error (or Infallible), then use init!.

The syntax is identical to try_pin_init!. You need to specify a custom error via ? $type after the struct initializer. The safety caveats from try_pin_init! also apply:

  • unsafe code must guarantee either full initialization or return an error and allow deallocation of the memory.
  • the fields are initialized in the order given in the initializer.
  • no references to fields are allowed to be created inside of the initializer.

ยงExamples

use pin_init::{try_init, Init, zeroed};

struct BigBuf {
    big: Box<[u8; 1024 * 1024 * 1024]>,
    small: [u8; 1024 * 1024],
}

impl BigBuf {
    fn new() -> impl Init<Self, AllocError> {
        try_init!(Self {
            big: Box::init(zeroed())?,
            small: [0; 1024 * 1024],
        }? AllocError)
    }
}