Advanced Rust Design Patterns

Borrowed View Types

When a large struct has multiple fields and a method borrows &mut self, Rust's borrow checker treats the entire struct self as exclusively borrowed across the function call boundary—preventing the caller from simultaneously reading another field of self. The Borrowed View pattern solves this by either splitting a struct into disjoint sub-views or parsing raw byte buffers into zero-copy borrowed view structs (PacketView<'a>).

1. Splitting a Struct into Disjoint Borrowed Views (`split_mut`):
   `Engine { config, cache, metrics }`
        |  `.views_mut()`
        v
   `( &EngineConfig, &mut Cache, &mut Metrics )`
   Caller can read `config` while mutating `cache` and `metrics` simultaneously!

2. Zero-Copy Parser View Struct (`HeaderView<'a>`):
   Raw Buffer `&'a [u8]`  ===[ Validates once ]===>  `HeaderView<'a> { topic: &'a str, payload: &'a [u8] }`
   (Zero heap allocations! Lifetimes guarantee `HeaderView<'a>` cannot outlive the backing buffer!)

1. Solving Inter-Method Borrow Conflicts with Disjoint View Structs

Inside a single function body, Rust's borrow checker understands disjoint field borrowing: you can borrow &self.config and &mut self.cache at the same time. However, if you factor that logic into a helper method fn lookup(&mut self) -> &Config, the method signature &mut self borrows all fields of self, blocking simultaneous access to self.cache!

Exposing a .split_views_mut(&mut self) method returns a tuple or dedicated view struct holding disjoint references to the individual fields:

pub struct Renderer {
    palette: [u32; 4],
    framebuffer: Vec<u32>,
}

/// A borrowed view struct holding disjoint references into `Renderer`.
pub struct RenderView<'a> {
    pub palette: &'a [u32; 4],
    pub framebuffer: &'a mut [u32],
}

impl Renderer {
    pub fn new(width: usize, height: usize) -> Self {
        Self {
            palette: [0x0000_0000, 0x00FF_0000, 0x0000_FF00, 0x0000_00FF],
            framebuffer: vec![0; width * height],
        }
    }

    /// Splits `&mut self` into an immutable borrow of `palette` and a mutable borrow of `framebuffer`!
    pub fn view_mut(&mut self) -> RenderView<'_> {
        RenderView {
            palette: &self.palette,
            framebuffer: &mut self.framebuffer,
        }
    }
}

2. Zero-Copy Borrowed Parser Views (MessageView<'a>)

Instead of allocating owned String and Vec<u8> copies when parsing network frames or log lines, a zero-copy view struct (MessageView<'a>) borrows &'a str and &'a [u8] slices directly from the caller's input buffer:

#[derive(Debug, PartialEq, Eq)]
pub struct LogRecordView<'a> {
    pub timestamp: &'a str,
    pub level: &'a str,
    pub message: &'a str,
}

impl<'a> LogRecordView<'a> {
    /// Parses a `"TIMESTAMP [LEVEL] MESSAGE"` line with ZERO heap allocations!
    pub fn parse(line: &'a str) -> Option<Self> {
        let (timestamp, rest) = line.split_once(" [")?;
        let (level, message) = rest.split_once("] ")?;
        Some(Self {
            timestamp: timestamp.trim(),
            level: level.trim(),
            message: message.trim_end(),
        })
    }
}

fn main() {
    // 1. Disjoint struct view mutation:
    let mut renderer = Renderer::new(2, 2);
    let view = renderer.view_mut();
    for (i, pixel) in view.framebuffer.iter_mut().enumerate() {
        // Read `view.palette` while mutating `view.framebuffer` simultaneously!
        *pixel = view.palette[i % view.palette.len()];
    }
    assert_eq!(renderer.framebuffer[1], 0x00FF_0000);

    // 2. Zero-copy borrowed parser view:
    let raw_line = "2026-10-27T12:00:00Z [INFO] Server listening on 127.0.0.1:8080\n";
    let record = LogRecordView::parse(raw_line).unwrap();
    assert_eq!(record.level, "INFO");
    assert_eq!(record.message, "Server listening on 127.0.0.1:8080");

    println!(
        "Zero-copy LogRecordView: ts={}, level={}, msg={:?}",
        record.timestamp, record.level, record.message
    );
}
Zero-copy LogRecordView: ts=2026-10-27T12:00:00Z, level=INFO, msg="Server listening on 127.0.0.1:8080"