From/TryFrom 的 Rust 实现应该针对引用还是值? [英] Should Rust implementations of From/TryFrom target references or values?
问题描述
我应该写:
impl<'a> From<&'a Type> for OtherType
或者应该是
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.
在 C++ 中,我会在值上定义函数 over/method 并在 const 引用上调用它.
In C++, I would define the function over/method on values and calling it on const references.
是否有从impl Trait
到impl<'a>的自动推导?特性<&'a Type>
?
推荐答案
From/TryFrom 的 Rust 实现应该以引用或值为目标吗?
Should Rust implementations of From/TryFrom target references or values?
是的,他们应该.
这里没有技巧:实现特征以转换您拥有的任何类型.如果你有一个 String
,实现它从 String
s 转换.如果您有 &str
,请将其实现为从 &str
转换.如果两者都有,请为两者都实施.
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.
是否有从impl Trait
到impl<'a>的自动推导?特性<&'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)
}
}
编译器没有明显正确的方法来实现对 String
的引用.但是,您可以自己实现它:
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())
}
}
<小时>
如果您不能使用传入的分配,则没有太多理由按值接受参数,因此您不妨接受一个引用.但是,我想说不太将From
用于此类转换——不过也并非闻所未闻.
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.
这篇关于From/TryFrom 的 Rust 实现应该针对引用还是值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!