Skip to main content

Posts

Showing posts with the label Systems Programming

Rust Async Patterns: Solving 'Cannot Move Out of Shared Reference' with Pinning

  One of the most notoriously difficult hurdles in async Rust—specifically when implementing manual   Future   types or middleware—is the compilation error:   cannot move out of ... which is behind a shared reference   or   cannot borrow data in a '&' reference as mutable . When you encounter this inside a  Future::poll  implementation, it is usually a symptom of a misunderstood memory model regarding  Pin . You are attempting to access a field of a struct that is structurally pinned, but you are not projecting that pin correctly to the field. This post dissects why naive field access fails in async contexts and demonstrates the correct implementation using structural pinning. The Root Cause: Pinning and Memory Stability To understand the error, we must look at the signature of the  Future  trait: pub trait Future { type Output; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::O...

Rust Ownership: Understanding Pinning and Self-Referential Structs

  One of the most abrupt complexity spikes in Rust occurs when you attempt to define a struct where one field refers to another field within the same struct. This is the "Self-Referential Struct" problem. It is a mandatory hurdle for developers building custom async executors, zero-copy parsers, or implementing intrusive linked lists. The compiler will reject any naive attempt to create this structure with lifetime errors, usually citing that a value is being moved while borrowed. To solve this, we must drop down to  std::pin  and raw pointers, manually enforcing the invariants that the borrow checker cannot. The Root Cause: Moves and Memory Addresses To understand why Rust forbids self-references by default, you must understand the mechanical implication of a "Move." In Rust, types are  Unpin  by default. This means the compiler is free to memcpy the bits of your struct from one stack slot to another, or from the stack to the heap, at virtually any time (e.g., ...