macro_rules! pin_init {
    ($(&$this:ident in)? $t:ident $(<$($generics:ty),* $(,)?>)? {
        $($field:ident $(: $val:expr)?),*
        $(,)?
    }) => { ... };
}
Expand description

Construct an in-place initializer for structs.

The syntax is identical to a normal struct initializer:

struct Foo {
    a: usize,
    b: Bar,
}

struct Bar {
    x: u32,
}

let a = 42;

let initializer = pin_init!(Foo {
    a,
    b: Bar {
        x: 64,
    },
});

Arbitrary rust expressions can be used to set the value of a variable.

Init-functions

When working with this library it is often desired to let others construct your types without giving access to all fields. This is where you would normally write a plain function new that would return a new instance of your type. With this library that is also possible, however there are a few extra things to keep in mind.

To create an initializer function, simple declare it like this:


impl Foo {
    pub fn new() -> impl PinInit<Self, !> {
        pin_init!(Self {
            a: 42,
            b: Bar {
                x: 64,
            },
        })
    }
}

Users of Foo can now create it like this:

let foo = Box::pin_init(Foo::new());

They can also easily embed it into their own structs:

struct FooContainer {
    foo1: Foo,
    foo2: Foo,
    other: u32,
}

impl FooContainer {
    pub fn new(other: u32) -> impl PinInit<Self, !> {
        pin_init!(Self {
            foo1: Foo::new(),
            foo2: Foo::new(),
            other,
        })
    }
}