Should Rust implementations of From/TryFrom target references or values?

佐手、 提交于 2021-01-28 08:25:37

问题


Should I be writing:

impl<'a> From<&'a Type> for OtherType

Or should it be

impl From<Type> for OtherType

I'm having a difficult time finding the answer, perhaps due to a vocabulary failure on my part. I really don't particularly care about the reference-ness/value-ness of the argument.

In C++, I would define the function over/method on values and calling it on const references.

Is there an automatic derivation from impl Trait<Type> to impl<'a> Trait<&'a Type>?


回答1:


Should Rust implementations of From/TryFrom target references or values?

Yes, they should.

There's no trickery here: implement the traits to convert whatever types you have. If you have a String, implement it to convert from Strings. If you have a &str, implement it to convert from &strs. If you have both, implement it for both.

Is there an automatic derivation from impl Trait<Type> to impl<'a> Trait<&'a Type>?

No, and for good reason. For example, consider this conversion:

struct Filename(String);

impl From<String> for Filename {
    fn from(value: String) -> Filename {
        Filename(value)
    }
}

There's no obviously correct way for the compiler to implement that for a reference to a String. However, you can implement it yourself:

impl<'a> From<&'a str> for Filename {
    fn from(value: &'a str) -> Filename {
        String::into(value.to_owned())
    }
}

If you can't make use of the incoming allocation, then there's not much reason to accept the argument by value, so you might as well accept a reference. However, I'd say it's less common to use From for such conversions — not unheard of, though.



来源:https://stackoverflow.com/questions/48244892/should-rust-implementations-of-from-tryfrom-target-references-or-values

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