4 ms·
The article looks great and I’m looking forward to reading it; this comment is not a criticism of the article. This API is the only bad thing about Rust! .e
by da39a3ee 5y ago
The article looks great and I’m looking forward to reading it; this comment is not a criticism of the article.
This API is the only bad thing about Rust!
.expect("Could not read file")
It’s so unfortunate to have an API that reads
.expect("thing we don’t expect")
I think we should all just forget it’s there and use
.unwrap_or_else(|| panic!(“thing we don’t expect”))
- vaylian 5y ago"expect" is like the word "assert". You express which invariant should always be true and therefore there should be no failure. The use of `.expect("Could not read file")` is actually wrong, because it can fail.
- hvdijk 5y agoThat is not how Rust documents expect() should be used. Rust's own documentation (https://doc.rust-lang.org/std/result/ https://doc.rust-lang.org/std/result/) contains: let mut file = File::create("valuable_data.txt").unwrap(); file.write_all(b"important message").expect("failed to write message"); The use of .expect("Could not read file") is consistent with Rust's documentation. And I agree with OP that .expect() is poorly named. I wouldn't raise it as an issue on the work of others who just use Rust and are stuck with it though.
- rastignack 5y agoI also wish I could write: .or_panic(“unexpected fatal error”) Or .unwrap_or_panic