Pain-free self-referential/recursively-referential pinned types.
Because this crate optimizes for recursive references, it's much nicer to use for porting/copying C code than alternatives. However, the cost is that it requires generic associated types (GATs). Further, this is the only crate for self-referential types which supports additional lifetimes than the self-referential one (with the small ergonomic caveat that closures don't support where bounds for now, so a proper trait has to be used).
When using this crate, all you have to do is define your struct like you
would in C, and then tell selfref
about it. However, do watch out; the
following will not be usable, despite compiling:
use opaque;
// This is the actual self-referential struct.
// This is a "marker" type, used to tell `selfref` about the type.
// This is actually the "type family" GAT pattern.
;
// This tells `selfref` about our type.
opaque!
That's because there's no way to create the reference
&'this MySelfRefStruct<'this>
before constructing the struct! That is,
you cannot do this:
But then, you cannot do this in C either. Instead, to make it usable, we
use an Option
and, to be able to set it, a Cell
, like so:
use Cell;
use opaque;
;
opaque!
and then we can use it:
// lines from the above example have been omitted
# use Cell;
#
use Holder;
use new_with_closure;
# use opaque;
use operate_in_closure;
#
#
#
# ;
#
# opaque!
Examples
This is a more complex example borrowing from an external lifetime:
use Cell;
use PhantomData;
use Pin;
use pin;
use Holder;
use NewWith;
use OperateIn;
use opaque;
;
opaque!