Here's the same function in Rust:
fn decomp(filename: &Path) -> Result<Vec<u8>, io::Error> {
let fd = File::open(filename)?; // File is automatically closed by its destructor.
let zd = GzDecoder::new(fd); // flate2::read::GzDecoder::new does not return an error.
let mut data = Vec::new(); // Rust makes the caller allocate the buffer for reads.
zd.read_to_end(&mut data)?;
Ok(data)
}
I think this is great. From a reader's perspective, it can dramatically improve readability in a lot of functions. From a writer's perspective, these kind of solutions make it easier to compose expressions without interleaving if-statements after every other line.Yes, sometimes you want to add context to your errors instead of using this syntax. But you can always use verbose syntax when it's needed, and terse syntax when it's not.