Rust Pinning
Written
- Useful Reading
- Pinning is useful in async because executors have references to Futures while polling. If the executor tries to use a future that was moved, then bad things happen. So the Pin keeps it in one place while the executor can poll it.
Pin<Box<T>>
is a pattern that shows up a lot- This is similar to using an
Arc<Mutex<T>>
or similar for lifetimes. It's not the most efficient way to write things but can be a lot easier to put together. - It allows a type that is normally
!Unpin
to be used where anUnpin
is needed, because the pinned type is then the Box and while the Box value can move, the value that it points to will always stay in the same location on the heap until it is deallocated, as required by thePin
semantics.
- This is similar to using an