Short question about the question mark operator

Hi folks,

yesterday I was reading this article about anyhow and when looking at the first code snippet I was wondering why it is not necessary to put the Error value explicitly in a Box? Is this some kind of ergonomic feature from the question mark operator?

Regards
keks

The ? operator will expand something like

let bytes = std::fs::read("file.txt")?;

into something like this

let bytes = match std::fs::read("file.txt") {
  Ok(b) => b,
  Err(e) => {
    return Err(e.into());
  }
};

There is a From impl which converts from any type implementing std::error::Error into an Box<dyn std::error::Error>, so the conversion happens automatically.

6 Likes

Ahhh I see! :slight_smile: That answers my question. Thank you very much!

Not really, the reason you don't need explicit boxing is that Box<dyn Error> implements From<E: Error>. As @Michael-F-Bryan showed you, the ? operator will utilise the Into<Box<dyn Error>> implementation of E, which is automatically implemented for E thanks to the implementation of From<E> for Box<dyn Error> I've linked above (because From<T> for U means you get a free implementation of Into<U> for T).

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.