I am trying to read in a file until the end 2 bytes at a time. I want to catch the EOF error. I have this code:
loop {
let binary = match file.read_be_u16() {
Ok(binary) => binary,
Err(e) => panic!("Can't read from file: {}, err {}", filename, e),
// Can I catch this EOF error here?
};
println!("{:?}", binary);
}
Being new to Rust I'm not really too aware of the "Rusty" way to do things (so not sure if this would be discouraged) but I personally find...
... to be more readable than...
(Not sure what other errors we could expect to get...)
Obviously, in other situations where the match guards might not be the same - the way that we're repeating
e.kind()
- we couldn't use the nestedmatch
Note: Works as of
rustc 1.25.0 (84203cac6 2018-03-25)
I figured it out. I changed this line to check the error type! Hope this helps others.
You can match the kind as part of the pattern, using some more advanced features of pattern matching:
The first variant means “an
Err
containing anIoError
wherekind
isIoErrorKind::EndOfFile
and all the other fields are whatever you like”. The second then means “any otherErr
, binding the contained value to the variable namee
”.At least rustc version rustc 1.17.0 (56124baa9 2017-04-24) doesn't allow destructuring the
Err
that Chris Morgan's answer used. I found this to work:Here is an example of matching a MySQL
IoError
: