0

I am new to rust and still trying to grab the concept of it. In Error trait docs it mentions

Error is a trait representing the basic expectations for error values, i.e., values of type E in Result<T, E>

But why Result is defined as Result<T,E> instead of Result<T,E:Error> to make it clearer?

6
  • 8
    Because the standard library rarely uses trait bounds on structs, they're usually on impl blocks, and more so because there is no reason to so restrict Result, it works perfectly well with things which don't implement Error itself. Commented Oct 7, 2023 at 10:32
  • 5
    A perfect example being .binary_search() which returns Result<usize, usize> Commented Oct 7, 2023 at 10:36
  • 1
    And another example are things like Rc::try_unwrap, which consume the value, try to convert it to something else and return the original value in case of error. Commented Oct 7, 2023 at 15:26
  • 1
    There is no point in restricting the use of Result like that. I suspect you might be thinking too much about exceptions in some other languages. Commented Oct 7, 2023 at 16:19
  • 1
    Note that while it is true that E is not required to implement Error, the aforementioned cases are actually a design mistake (at least try_unwrap()). The error type should at least implement Debug, so that unwrap() and expect() can work. A better candidate is Box<dyn Error> (or other variants such as anyhow::Error, which is an error type but does not implement Error. Commented Oct 7, 2023 at 18:22

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.