问题
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 String
s. If you have a &str
, implement it to convert from &str
s. If you have both, implement it for both.
Is there an automatic derivation from
impl Trait<Type>
toimpl<'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