I have taken the source code example from error_chain:
use std::io::Write;
let stderr = &mut ::std::io::stderr();
let errmsg = "Error writing to stderr";
writeln!(stderr, "error: {}", e).expect(errmsg);
I sort of guess what expect() does... but I am likely wrong. I can not understand where expect function is defined.
Could you please explain what expect does here? and how do you find a definition of a function like expect, if IDE (Intellij) is of no help?
Great! How have you figured out that expect is from the Result looking only at writeln! and not having other knowledge? Basically, how do you find return type of writeln! macro?
Using the search function in the standard library documentation, the expect method is only defined for Option and Result. writeln! is doing IO which can fail, so it would make sense that it would return a Result.
Thanks. That search strategy is an interesting one. We are lucky that expect is defined only for 2 types and assuming that one type is a perfect fit for a macro to return...
Method 1: The deliberate type error (an old favorite)
fn main() {
use std::io::Write;
let stderr = &mut ::std::io::stderr();
let errmsg = "Error writing to stderr";
// deliberate type error
let () = writeln!(stderr, "error: {}", e);
}
error[E0308]: mismatched types
--> src/main.rs:5:9
|
5 | let () = writeln!(stderr, "error: {}", e);
| ^^ expected enum `std::result::Result`, found ()
|
= note: expected type `std::result::Result<(), std::io::Error>`
found type `()`