Drop — custom cleanup on value going out of scope.
Implementation:
1struct MyResource {2 data: Vec<u8>,3}45impl Drop for MyResource {6 fn drop(&mut self) {7 println!("Dropping resource with {} bytes", self.data.len());8 // Cleanup here9 }10}1112{13 let r = MyResource { data: vec![0; 1024] };14 // Using resource...15} // drop() called here
Drop order:
1let a = MyResource { data: vec![] };2let b = MyResource { data: vec![] };3drop(a); // Explicit drop4// b dropped at end of scope
Key: Drop for RAII, called automatically.