Defer in Rust
In Rust, we use the Drop
trait to ensure that a function is called when a value goes out of scope, which is similar to Go’s defer
. This is often used for cleanup purposes.
In this Rust version:
We use
File::create
to create a file, which returns aResult
. We use pattern matching to handle the result.Instead of explicitly deferring the close operation, we rely on Rust’s RAFI (Resource Acquisition Is Initialization) principle. The
File
type implements theDrop
trait, which automatically closes the file when it goes out of scope.We use the
write!
macro (specificallywriteln!
for writing with a newline) to write to the file.Error handling is done using
Result
and the?
operator or explicit matching.
Running the program confirms that the file is created, written to, and then automatically closed when it goes out of scope:
In Rust, resource cleanup is typically handled automatically through the Drop
trait, which provides better safety guarantees compared to manual resource management. This approach helps prevent resource leaks and makes the code safer and more concise.