What is `std::pin::Pin` in Rust?

14 points by vrongmeal


avillegaz

std::pin::Pin is the Monad of the Rust world. Once you understand it you are forced to write a blogpost about it.

wrs

Might be good to address a couple of things that hit me (and others) when trying to understand Pin:

Once I started doing these mental translations things made more sense to me. Of course, maybe I'm still confused and have just been lucky! :)

jjdh

I feel I’ve asked this before and someone gave a thoughtful reply.. but I can’t remember it. Pin, as it was explained to me, came out of async where local variable references become self-references in the blob of data that represents the state machine for a given function.

Ok fine, if the async state were moved, all those local variable references would point to the old invalid location.

But, that’s only true because they are real pointers, like full absolute references. My question is: Why was the solution to this to remove the ability to move, instead of making the references be relative?

Is the answer mostly “because there is a million engineer years gone into the compiler and CPU and OS really, really, really getting pointers”, so pointers are just better in so many ways that its better to have to Pin everywhere, or is there some real hard reason that makes relative references not actually work as an alternative solution?

ngoldbaum

Probably worth noting somewhere in this post that !UnPin is only expressible in nightly rust, which is the main reason PhantomPinned is a thing.

polywolf

Overall I think this is a good explainer to have in addition to the official Rust documentation, eases into the issues a bit nicer.

However, I think leading with the self-referential struct makes things more confusing than if it had been omitted. Specifically, in the introduction:

Hence, we need a way to prevent moving SelfRef once those self-references have been established.

started me thinking about the wrong problem, preventing moves entirely, when really the core of it is explained much later:

Pin does not physically prevent values from moving. Instead, it is a type-level guarantee that the value will not be moved through that pointer.

It is not possible to prevent moves, so we use Pin to expose self-referential data only behind exclusive references in a safe API. Maybe I understand Pin too much already, but maybe tweaking the presentation slightly could help readers not get lost.