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

强颜欢笑 提交于 2020-12-09 14:00:43

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/62566447/what-are-the-pros-and-cons-of-impl-tryfrombar-for-foo-vs-impl-frombar-for-re

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!