Running Code on Cleanup with the Drop Trait
The Drop trait lets you run code automatically when a value goes out of
scope. This is the foundation of resource management in Rust and Oxide.
Implementing Drop
public struct Connection {
host: String,
}
extension Connection {
public static fn new(host: String): Connection {
Connection { host }
}
}
extension Connection: Drop {
mutating fn drop() {
println!("Closing connection to \(self.host)")
}
}
When a Connection is dropped, the drop method runs automatically.
Dropping Early
You can drop a value before the end of its scope by calling drop:
fn main() {
let conn = Connection.new("db.example.com")
drop(conn)
println!("Connection closed early")
}
This is useful when you want to release resources as soon as possible.