ownership

Rust Struct fields: destruction order

When a struct is destroyed, its custom Drop method runs first if present, then its fields are destroyed in declaration order. This differs from the reverse declaration order of local variables. Expected output (not executed): pair first second Why: The custom destructor runs before the fields, whose order follows their declarations, not literal initialization order. Common mistake: Relying on the order of fields in the struct literal to choose destruction order.

Formal Syntax & Structure

rust syntaxrust
struct Pair { first: T, second: T }

Working Example

Example Snippetrust
struct Log(&'static str);impl Drop for Log {    fn drop(&mut self) { println!("{}", self.0); }}struct Pair { _first: Log, _second: Log }impl Drop for Pair {    fn drop(&mut self) { println!("pair"); }}fn main() {    let _pair = Pair { _second: Log("second"), _first: Log("first") };}
Rust Reference