5 ms·
It's interesting to take note of the actual Rust `File` object: https://doc.rust-lang.org/std/fs/struct.File.html https://doc.rust-lang.org/std/fs/struct.File.h
by ChrisSD 7y ago
It's interesting to take note of the actual Rust `File` object: https://doc.rust-lang.org/std/fs/struct.File.html https://doc.rust-lang.org/std/fs/struct.File.html
`open` is a static function on the `File` object and an instance of `File` does not have a `close` method at all. So, as in this article, an instance of `File` can only be created if `open` succeeded and the file will be closed when dropped (either implicitly or explicitly). For example:
fn main() -> std::io::Result<()> {
// a file object is only created if File::create is successful
// otherwise main returns an error
let mut file = File::create("foo.txt")?;
file.write_all(b"Hello, world!")?;
Ok(())
} // file closed here, no close method needed.
This contrasts with many other languages where a class instance can be in an invalid state. This is something the typestate pattern helps to avoid.
- ridiculous_fish 7y agoWhy isn't there a close method? It seems strange to omit this, given that close can return an error. edit: also closing stdin/stdout is common.
- empath75 7y agoIt automatically closes once it’s out of scope.
- winstonewert 7y agoYou can see here some discussion of that question: https://github.com/rust-lang/rust/issues/32255 https://github.com/rust-lang/rust/issues/32255 https://github.com/rust-lang/rust/issues/59567 https://github.com/rust-lang/rust/issues/59567
- ChrisSD 7y agoThere's a sync_all method that will make sure all data and metadata is written or else return an error. This may be used at any time, not just when closing the file, and it is expensive so it does make sense to have a separate method for that case.