Jon Gjengset explains the Pin and Unpin types in Rust, detailing why they are needed for self-referential structs and async programming.
With the Future trait stabilized and async/await coming soon, many more people are being exposed to the Pin type and its sibling trait Unpin. In this video, we dive deep into what these types are, why they are needed, how they work, and how to use them. We also dig into the connection to Futures and async/await, and discuss how you safely move from old code that does not use pinning to new code that does.
This is pretty dense and subtle material, but hopefully serves as a good and thorough overview of pinning in Rust. If you want to know how it all fits together, this stream probably has you covered! To help you navigate, here are the major transition points:
— Introduction
— What's the problem we're trying to solve?
— How does pinning help?
— What is Unpin?
— Working with pinned types
— An example of implementing Future
— Pin::new vs Pin::new_unchecked
— The problem with Drop
— Quick recap
— Why impl Unpin is safe
— Structural pinning
— The curious case of Box::pin
— Avoiding unsafe with pin-project
— Why is Pin::set okay?
— Pinning beyond Future
— Some quick questions
— Real-world examples of transitioning to Pin in tower
— pin-project and Drop
— Q&A!
You can vote for the next stream topic at jon.thesquareplanet.com/live-coding/ !
Live version with chat history here: youtube.com/watch?v=UuuhMDinEBg
Why it's here
3 people recommend this
What people say. Recommended as an invaluable, deep-dive explanation of Rust's pinning semantics and how they relate to async/await.
t
theossuaryon Hacker News • Recommends
On “Effing-mad, an effect library for Rust”
Jon Gjengset's stream on pin/unpin is invaluable for understanding Pin semantics: link to this video But the 10000 ft view is: Pin lets you tell Rust to never ever move a piece of memory. This is almost always done because the piece of memory has pointers into itself (it's self referencial) which would be come invalid if moved.
On “Things you can’t do in Rust (and what to do instead)”
…on. Accessing them would trigger undefined behavior. Self-referencing is only acceptable, if the struct is guaranteed not to move. Rust does provide a mechanism to provide such a guarantee with std::pin but outside of async code, you probably don't want to be using it. std::pin: link If you're curious about pinning and have a few hours to spare, link to this video is a great video that explains it in detail.…
there is a chapter on async in comprehensive rust and rustbook which ought to bring you up to speed there is the async book but it is largely unfinished you can watch John Gjengset's crust of rust async, decrusting tokio, and why what, and how of pinning in rust then there are tokio-lessons and tokio tutorial which teach how to use tokio runtime and there are also good blogposts by phil-oop and rose wright on how async works linklinklinklinklinklink to this videolinklinklinklink