Re: [PATCH] rust: pin-init: document self-referential feature
From: Gary Guo
Date: Tue Dec 01 2026 - 08:44:51 EST
On Thu Nov 26, 2026 at 9:56 AM GMT, Philipp Stanner wrote:
> On Tue, 2026-11-24 at 22:16 +0000, Gary Guo wrote:
>> From: Gary Guo <gary@xxxxxxxxxxx>
>>
>> Add a section to the documentation of `#[pin_data]` macro about
>> the safe self-referential creation feature.
>
> Thx for writing this, that's very useful. I read through it. Just some
> comments below:
>
>> +/// Here the field `part` captures the field lifetime `'msg` and thereby borrows the field `msg`.
>> +/// A field may only borrow from fields declared after it: fields are dropped in declaration
>> +/// order, so the borrowing field is then always dropped before the field it borrows. Structs
>> +/// with borrowed fields or captured lifetimes do not implement `Unpin`.
>
> Unpin is something the user would have to implement for his struct,
> isn't it? So are you saying here that the macros do not generate Unpin?
> Why's that mentioned, do you expect anyone to need / expect to have
> Unpin?
If you use `pin_data`, an `Unpin` implementation is controlled by `pin_data`. I
reckon this is also under-documented, but most users won't need to know anyway
(unless they manually implement `Unpin` and hit a duplicate implementation
errror). Typically, if all fields are `Unpin`, then the struct will be `Unpin`
despite use of `#[pin_data]`.
For self-referential struct, `pin_data` generates a never-satisfied
implementation and thus effectively never implement `Unpin` but also block user
from implementing it. This is true even if all fields are `Unpin`.
E.g.
struct Foo {
y: &'x u32,
x: u32,
}
all fields are `Unpin` but `Foo: !Unpin`.
I'd probably not expand it out because most users won't need to care.
>
>> +/// ## Mutable Borrows
>> +///
>> +/// A field is only shared-borrowed by default. To also allow `&mut` borrows, mark the borrowed
>
> I think the English-bros say "To also allow *for* …"
>
>> +/// field with `#[borrowed(mut)]`:
>> +///
>> +/// ```
>> +/// # use pin_init::*;
>> +/// #[pin_data]
>> +/// struct MutSelfRef {
>> +/// part: &'mut_msg mut str,
>> +/// #[borrowed(mut)]
>> +/// mut_msg: String,
>> +/// }
>> +///
>> +/// stack_pin_init!(let foo = pin_init!(MutSelfRef {
>> +/// mut_msg: "hello world".to_owned(),
>> +/// part: &mut mut_msg[..5],
>> +/// }));
>> +/// foo.as_mut().with_project(|proj| proj.part.make_ascii_uppercase());
>> +/// assert_eq!(*foo.part(), "HELLO");
>
> Is #[borrowed(mut)] basically a better alternative to UnsafeCell?
For some use cases perhaps, although `#[borrowed(mut)]` would make the field
disappear from all `&self` and `Pin<&mut Self>` so you can only access it via
the mutable reference that is created during initialization. If it fits your use
cases then it's a good replacement, but no generally true.
>
>> +/// ## Existential Lifetimes
>> +///
>> +/// A field lifetime ties a borrow to a specific field. Sometimes a field should instead borrow
>> +/// from something outside the struct that merely outlives one of the struct's lifetime
>> +/// parameters.
>>
>
> "the struct's lifetime parameters" == "the struct's members' lifetime
> parameters" ?
The current wording is correct. Struct have generic parameters, and it can
either be lifetime parameter, type parameter or const parameter. Members don't
have parameters.
>
>
> It doesn't get fully clear to me why you mention "sometimes should
> instead borrow from sth outside the struct". You seem to be referring
> to "normal" structs that borrow something with a normal lifetime. So it
> reads as if you fear that users might use self-referencial structs when
> really their struct should just borrow something from the outside.. why
> do you mention that, when would the user borrow something that the
> struct already has which shouldn't be in there?
No this feature is somewhat independent of self-referential borrow. You can have
a struct that just borrow from outside the struct only, but use the `exists`
feature:
struct Foo<'a> where exists<'inv>: 'a {
foo: Mutex<&'inv ()>,
}
This is similar to
struct Foo<'a> {
foo: Mutex<&'a ()>,
}
However the existential lifetime causes the struct to be covariant over `'a` and
not invariant. This becomes part of self-referential series because they're both
erased lifetimes and the implementation are remarkably similar (and shares
almost all the code).
>
>
>> +/// ## Projections and Accessors
>> +///
>> +/// Since field lifetimes are not parameters of the struct, borrows of the struct cannot carry
>
> s/parameters/members ?
>
>> +/// them. This macro therefore generates several methods for accessing the fields:
>> +///
>> +/// - `project(self: Pin<&mut Self>)` — the pin projection: `#[pin]` fields are projected as
>> +/// `Pin<&mut T>`, all other fields as `&mut T`. Fields that capture a field lifetime covariantly
>> +/// are only projected as (possibly pinned) shared references; fields with invariant field
>> +/// lifetime capture are omitted entirely.
>
> Means all self-referential fields are invisible? I would maybe mention
> that project() should be the preferred accessor for users.
Depend on what you mean by preferred? If `project()` works then yes it is the
best. But many cases you do need to use `with_project()`/`with_project_ref()` or
the accessor methods so there's no single recommendation possible.
>
>> +/// - `with_project(self: Pin<&mut Self>, f)` — calls `f` with a projection in which every
>> +/// visible field has its actual field lifetime, so even invariant captures are visible.
>> +/// - `with_project_ref(self: Pin<&Self>, f)` — the shared version of `with_project`.
>
> Thus, the user only wants these two if he needs to access self-
> referential fields?
If you never access self-referential fields then you just need `project()` (or
directly access the field), which is why these methods didn't exist before the
pin-init self-ref series.
>
>
>> +///
>> +/// For all projections, shared borrow fields are only accessible with shared references, and
>> +/// mutably borrowed fields are omitted (they are only accessible through the fields that borrow
>> +/// them).
>> +///
>> +/// Every field (except those borrowed mutably) that captures field lifetimes also gets an accessor
>> +/// method,
>>
>
> Are you refering to my_struct.member(), or to
> my_struct.with_member(|member| {… ) ?
It's literally the next sentence?
>
>> because they cannot be directly accessed. `fn field(&self)` is generated if all of its
>> +/// captures are covariant, otherwise `fn with_field(&self, f)` is generated where `f` is called
>> +/// with the field at its captured lifetimes.
>> +///
>> +/// ```
>> +/// # use pin_init::*;
>> +/// # #[pin_data]
>> +/// # struct SelfRef {
>> +/// # part: &'msg str,
>> +/// # msg: String,
>> +/// # }
>> +/// # stack_pin_init!(let foo = pin_init!(SelfRef {
>> +/// # msg: "hello world".to_owned(),
>> +/// # part: &msg[..5],
>> +/// # }));
>> +/// foo.as_mut().with_project(|proj| {
>> +/// *proj.part = &proj.msg[6..];
>> +/// });
>> +/// assert_eq!(*foo.part(), "world");
>> +/// foo.as_ref().with_project_ref(|proj| {
>> +/// assert_eq!(*proj.part, "world");
>> +/// });
>
> So if you need one field only you would do:
>
> foo.as_ref().with_part(|part| {
> pr_info("{}", part);
> });
Ah I didn't include an example of invariant capture in the example above.
I should spell it out (and perhaps add comment in the doc code block too).
Best,
Gary