Pinning an !Unpin type to the heap gives our data a stable address so we know that the data we point to can't move after it's pinned. In contrast to stack pinning, we know that the data will be pinned for the lifetime of the object.
But I don't fully understand. Why is pinning on the heap different than pinning on the stack? I've read that chapter of the book a few times, can someone please elaborate?
In contrast to stack pinning, we know that the data will be pinned for the lifetime of the object.
As in, the type system ensures this guarantee for heap pinning while it can't for stack pinning (and you need too use unsafe). IMO however, when you're using the macro for stack pinning from pin_utils, instead of pinning with the unsafe fn, you get just as strong a safety guarantee, so there is pretty much no difference anymore between the two. (Other than the benefits that the heap always offers: that you can move the value up the call stack.)
If you have a Box<T>, then you are guaranteed that moving the box doesn't move the T, where here moving means that it gets a new address in memory. However if you have a T and move it, then it is moved.