// BAD CODE: This example is intentionally wrong. pub struct BagOfApples { count: usize, // In the example code, this self-reference is mostly useless. // This is just to keep the example code simple - the emphasis is // on the effects of pinning, not why a type may be designed to need it. self_reference: *mut BagOfApples, } impl BagOfApples { pub fn new() -> Self { BagOfApples { count: 0, // We cannot set this here because we have not yet // created the BagOfApples - there is nothing to reference. self_reference: ptr::null_mut(), } } /// Call this after creating a BagOfApples to initialize the instance. pub fn initialize(&mut self) { self.self_reference = self; } pub fn count(&self) -> usize { assert!( !self.self_reference.is_null(), "BagOfApples is not initialized" ); // SAFETY: Simple read-only access to the count field, which // is safe. We do it via the pointer for example purposes. unsafe { (*self.self_reference).count } } } // BAD CODE: This example is intentionally wrong.