From<Error> not working

Ever done something hundreds of times before, then you're doing (what you think is) the same thing again, but it doesn't work?

What am I doing wrong in this piece of code?

Why isn't it picking up on the From conversion trait?

The error is:

error[E0308]: mismatched types
  --> src/
33 |   fn do_bar_thing(&self, foo: &Foo<T>) -> Result<(), BarError> {
   |                                           -------------------- expected `std::result::Result<(), BarError>` because of return type
34 |     foo.do_foo_thing()
   |     ^^^^^^^^^^^^^^^^^^ expected enum `BarError`, found enum `FooError`
   = note: expected enum `std::result::Result<_, BarError>`
              found enum `std::result::Result<_, FooError>`

In Rust you need to be explicit about type conversion on most cases. For this case the ? operator does convert the error type.

1 Like

Ah! I've always through the magic was related to Result -- so it's ? that does the implicit conversion, then. TIL, etc. :slight_smile:

Result is "just" another type in Rust that the compiler knows nothing about. The ? performs .into() on the error variant, which ends up calling the From impl.

1 Like

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.