Pinning in Rust 237 Here, we pin Maybe Self Ref to the heap and initialize it. We print out the value of a and then mutate the data through the self-reference in b, and set its value to 2. If we look at the output, we'll see that everything looks as expected: Finished dev [unoptimized + debuginfo] target(s) in 0. 56s Running `target\debug\x-pin-experiments. exe` 0 2 The pinned value can never move and as users of Maybe Self Ref, we didn't have to write any unsafe code. Rust can guarantee that we never (in safe Rust) get a mutable reference to Maybe Self Ref since Box took ownership of it. Heap pinning being safe is not so surprising since, in contrast to the stack, a heap allocation will be stable throughout the program, regardless of where we create it. Important This is the preferred way to pin values in Rust. Stack pinning is for those cases where you don't have a heap to work with or can't accept the cost of that extra allocation. Let's take a look at stack pinning while we're at it. Pinning to the stack Pinning to the stack can be somewhat difficult. In Chapter 5, we saw how the stack worked and we know that it grows and shrinks as values are popped and pushed to the stack. So, if we're going to pin to the stack, we have to pin it somewhere “high” on the stack. This means that if we pin a value to the stack inside a function call, we can't return from that function, and expect the value to still be pinned there. That would be impossible. Pinning to the stack is hard since we pin by taking &mut T, and we have to guarantee that we won't move T until it's dropped. If we're not careful, this is easy to get wrong. Rust can't help us here, so it's up to us to uphold that guarantee. This is why stack pinning is unsafe. Let's look at the same example using stack pinning: ch09/d-pin/src/main. rs fn stack_pinning_manual() { let mut x = Maybe Self Ref::default(); let mut x = unsafe { Pin::new_unchecked(&mut x) }; x. as_mut(). init(); println!("{}", x. as_ref(). a); *x. as_mut(). b(). unwrap() = 2;