Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the pros and cons of impl TryFrom<Bar> for Foo vs impl From<Bar> for Result<Foo, ()> for fallible conversions?

Tags:

rust

Starting from Rust 1.34, we can write fallible conversions between types by implementing the TryFrom trait:

struct Foo(i32);
struct Bar;

impl TryFrom<Bar> for Foo {
    type Error = ();
    fn try_from(_b: Bar) -> Result<Foo, ()> {
        Ok(Foo(42))
    }
}

In Rust 1.41, the orphan rule has been relaxed so we can also write:

struct Foo(i32);
struct Bar;

impl From<Bar> for Result<Foo, ()> {
    fn from(_b: Bar) -> Result<Foo, ()> {
        Ok(Foo(42))
    }
}

According to this trial both solutions seem to work equally well.

What are the pros and cons of having either or both approach? How to choose from the two?

This question is important to the ecosystem. For example, a crate writer needs advice on whether to support TryFrom, From or both. A macro writer will need to know if it needs to handle both cases, etc. This depends on the status of the ecosystem today, and can't be answered easily.

like image 828
Earth Engine Avatar asked Jun 25 '20 01:06

Earth Engine


1 Answers

In TryFrom, the error is an associated type—it is fixed by the type Bar. This is not the case for From, and indeed you could implement From for more than one error type. Unless you intend to do that (which is rather strange), you should stick to TryFrom.

like image 113
Lambda Fairy Avatar answered Oct 04 '22 02:10

Lambda Fairy