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.