Macro pinned_init::pin_init
source · [−]macro_rules! pin_init {
($(&$this:ident in)? $t:ident $(<$($generics:ty),* $(,)?>)? {
$($field:ident $(: $val:expr)?),*
$(,)?
}) => { ... };
(@this($($this:ident)?), @type_name($t:ident $(<$($generics:ty),*>)?), @typ($ty:ty), @fields($($field:ident $(: $val:expr)?),*)) => { ... };
}Expand description
Construct an in-place initializer for structs.
The syntax is identical to a normal struct initializer:
#[pin_project]
struct Foo {
a: usize,
b: Bar,
}
#[pin_project]
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 {
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:
#[pin_project]
struct FooContainer {
#[pin]
foo1: Foo,
#[pin]
foo2: Foo,
other: u32,
}
impl FooContainer {
fn new(other: u32) -> impl PinInit<Self> {
pin_init!(Self {
foo1: Foo::new(),
foo2: Foo::new(),
other,
})
}
}