4 ms·
> File's Drop implementation ignores the return code of fclose() Yeah, and it bothers me that I can't call `close` and check for errors. All you need is somet
by rectang 6y ago
> File's Drop implementation ignores the return code of fclose()
Yeah, and it bothers me that I can't call `close` and check for errors. All you need is something like this:
pub fn close(self) -> io::Result<()> {
let status = unsafe { libc::close(self.fd) };
mem::forget(self); // prevent drop and invalid double-close
match status {
0 => Ok(()),
_ => Err(io::Error::new(ErrorKind::Other)),
}
}
Note that this function takes `self` not `&mut self`, so it consumes the resource and prevents further use. Then `mem::forget` prevents `drop` from running.
See discussion at https://github.com/rust-lang/rust/issues/59567 https://github.com/rust-lang/rust/issues/59567