What is the expect() function for writeln! macro?


#1

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?


#2

https://doc.rust-lang.org/std/result/enum.Result.html#method.expect


#3

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?


#4

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.


#5

Thanks. That search strategy is an interesting one. We are lucky that expect is defined only for 2 types :slight_smile: and assuming that one type is a perfect fit for a macro to return…


#6

To find the type of any arbitrary expression:

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 `()`

Method 2: Find an IDE which actually shows types

Edit: ooookay I just noticed you ARE using Intellij


#7

Method 1 - great trick, will use it.

Method 2 - I am using Intellij IDE. Unfortunately it does not show the type:
image


#8

For anyone using the Rust plugin for a JetBrain’s editor…

“parameter name hints”, in File -> Settings -> Editor -> General -> Appearance

You can turn the hints on or off. Whether they show you what you want or expect is another matter.


#9

I expect it to show correct type or tell me it can not be identified. In this case the type is not correct.


#10

IntelliJ Rust does not fully parse macros yet but it has hardcoded the return type of some built-in macros like println!(), assert!(), format!(), …

For write!() and writeln!() it currently always wrongly infers the type () but that should be fixable.

For more details please see this issue: