rustcompiler-errorsrust-result

Why doesn't Rustlings force me to consume a Result?


After a brief attempt, when I run the the Rustling test for exercises/error_handling/errorsn.rs, I get

---- test_ioerror stdout ----
thread 'test_ioerror' panicked at 'assertion failed: `(left == right)`
  left: `"uh-oh!"`,
 right: `"cannot parse integer from empty string"`', exercises/error_handling/errorsn.rs:69:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Line 69 has

assert_eq!("uh-oh!", read_and_validate(&mut b).unwrap_err().to_string());

Doing a bit of debugging I can see read_and_validate(&mut b) is returning,

Err(ParseIntError { kind: Empty })

My first attempt to remedy this was,

let num: i64 = line.trim().parse().or(Err("uh-oh!")?;

But this seemed senselessly awkward looking for uh-oh! in the code I saw,

Err(io::Error::new(io::ErrorKind::BrokenPipe, "uh-oh!"))

So I could tell at this point I wasn't supposed to write "uh-oh!" anywhere. Looking at the cause for my error, the bugged code they provide (which we're supposed to fix) has,

b.read_line(&mut line); # unmodified notice they don't have `?`

What I had to do was change it to the following,

b.read_line(&mut line)?; # I added the `?`
let num: i64 = line.trim().parse()?;

While that's all easy, it doesn't make sense. Looking up .read_line I see it returns a Result.

So my question at the end of all this is why do callers of .read_line not have to handle the errors it returns? It seems like the lesson from this Rustlings is almost trolling the user to tell them you can't rely on type-safety. Look at the docs, all of this seems to be undocumented. Rust even has a section entitled "Results must be used",

Result is annotated with the #[must_use] attribute, which will cause the compiler to issue a warning when a Result value is ignored. This makes Result especially useful with functions that may encounter errors but don't otherwise return a useful value. [...] If you do write that in Rust, the compiler will give you a warning (by default...

Where is this behavior documented? What other core functions allow errors to go unhandeld?


Solution

  • Rustlings does not show compiler warnings.

    What you would normally see are warnings, not errors. Rustlings does not reflect compiler warnings to the end user. So you see nothing.

    If you want to see the warnings, add

    #![deny(warnings)]
    

    However, there are a lot of warnings in the Rustlings code so it seems that that warning won't be promoted before one of the other warnings-promoted-to-errors stops compilation. Also rustlings watch will stop watching the second it encounters an error.