expression

Track a partially initialized array on early error

A prefix counter records how many slots hold live values. On early return the guard destroys exactly those slots. Increment only after a successful write. In production, a Vec or array of Option is usually simpler. The example uses nonpanicking destructors; cleanup after a destructor itself panics is not guaranteed. Expected stdout (not executed): error=true drops=2 Common mistake: Dropping all three slots even if initialization stopped after two.

Formal Syntax & Structure

rust syntaxrust
initialized prefix + Drop guard

Working Example

Example Snippetrust
#![deny(unsafe_op_in_unsafe_fn)]fn main() {    use std::{cell::Cell, mem::MaybeUninit};    struct Item<'a>(&'a Cell<u32>);    impl Drop for Item<'_> {        fn drop(&mut self) { self.0.set(self.0.get() + 1); }    }    struct Prefix<'a> { slots: [MaybeUninit<Item<'a>>; 3], len: usize }    impl Drop for Prefix<'_> {        fn drop(&mut self) {            while self.len > 0 {                self.len -= 1;                // SAFETY: the removed index was initialized and has not been dropped.                unsafe { self.slots[self.len].assume_init_drop(); }            }        }    }    fn prepare(count: &Cell<u32>) -> Result<(), &'static str> {        let mut guard = Prefix { slots: [const { MaybeUninit::uninit() }; 3], len: 0 };        for input in [true, true, false] {            if !input { return Err("invalid input"); }            guard.slots[guard.len].write(Item(count));            guard.len += 1;        }        Ok(())    }    let count = Cell::new(0);    println!("error={}", prepare(&count).is_err());    println!("drops={}", count.get());}
Rust Reference