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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With