3 ms·
In Rust this is achieved using `if let` for anything that uses `Result` and `Drop` (it's kinda neat how a few orthogonal features fit nicely together like that)
by pornel 7y ago
In Rust this is achieved using `if let` for anything that uses `Result` and `Drop` (it's kinda neat how a few orthogonal features fit nicely together like that):
if let Ok(f) = File::open(filename) {
f.read();
// drop(f) automatic here
}
But Rust's move semantics give you extra flexibility, because you don't have to close it if you don't want to.
let keep = None;
if let Ok(f) = File::open(filename) {
f.read();
if random() {
keep = Some(f);
}
}
// the file *may* be usable beyond the first scope,
// and it's still dropped correctly.
Values aren't dropped simply at the end of their initial scope (as in `with` or on-stack RAII), but after their last use, and language semantics allow the compiler to track globally where the last use is.
- steveklabnik 7y ago(drop types are still dropped at the end of lexical scope, even post NLL.)
- pornel 7y agoI've meant that if a value is moved, it won't be dropped in the scope it came from, but the one it's been moved to.