Hacker News new | ask | show | jobs
by VGHN7XDuOXPAzol 338 days ago
> what happens when there is an error reading the file?

the question mark `?` denotes the fact that the error is bubbled up (kind of like an exception, but with stronger typing and less silent)

2 comments

Specifically the ? symbol is currently implemented via the operator trait Try as Try::branch() which gets you a ControlFlow

If Try::branch gives us a ControlFlow::Break we're done here, return immediately with the value wrapped by Break [if any] inside an Err, otherwise we have ControlFlow::Continue wrapping a value we can use to continue with execution of this function.

This is type checked, so if the function says it returns Result<Goose, Dalek> then the type of the value wrapped in a ControlFlow::Break had better be Err(Dalek) or else we can't use our ? operator here.

Reifying ControlFlow here separates concerns properly - if we want to stop early successfully then control flow can represent that idea just fine whereas an Exception model ties early exit to failure.

Thanks for the info. I imagine that in this care, since it seems the error is not captured, it should end producing panic. So a question mark is used when the expected result is of type Result or Error. Also the web page, https://doc.rust-lang.org/rust-by-example/error/result.html, describe the result type as Ok(T) or Err(E), and indicates that is a richer version of Option.
Yeah, if `main` returns an error I think it exits with an error code and prints it out, so quite similar to a panic.

I think the blog post is not focussing on error handling too much, but in any case this is 'safe', just could likely be handled better in a real-world case.