[英]why does Rust's Add trait take ownership?
I am writing a toy BigInt class, and while I was implementing the Add trait
, I noticed that the it takes ownership of both sides.我正在写一个玩具 BigInt class,当我实现Add trait
时,我注意到它拥有双方的所有权。 What problem is that trying to solve, as opposed to borrowing them by reference?试图解决什么问题,而不是通过引用借用它们? Since I am using a Vec
as the underlying data structure, I cannot implement Copy
, and that makes it somewhat cumbersome to use.由于我使用Vec
作为底层数据结构,我无法实现Copy
,这使得使用起来有些麻烦。
An example of a (minor) inconvenience that it causes:它导致的(轻微)不便的示例:
let i = BigInt::new();
// - move occurs because `i` has type `BigInt`, which does not implement the `Copy` trait
let j = i + 16u32;
// --------- `i` moved due to usage in operator
let k = i + 32u32;
// ^ value used here after move
Again, I know I can just use .clone()
, but I am curious about in which ways this is helping the programmer.同样,我知道我可以只使用.clone()
,但我很好奇这在哪些方面帮助了程序员。
An example of why it's important to be able to take ownership is so that String + &str
can append to the existing string, instead of cloning it first.为什么能够取得所有权很重要的一个例子是String + &str
可以 append 到现有字符串,而不是先克隆它。
You can always implement Add
for references and .clone
ing inside of them.您始终可以在其中实现Add
for references 和.clone
。
struct A;
impl std::ops::Add for A {
// normal impl
}
impl<'a> std::ops::Add for &'a A {
// clone and delegate
}
fn main() {
A + A; // This still compiles
&A + &A; // This now compiles
&A + A; A + &A; // These won't compile, but you can add those impls too, if you'd like
}
However, you should probably only do this for Copy
types, to avoid the users being surprised by hidden allocations.但是,您可能应该只对Copy
类型执行此操作,以避免用户对隐藏的分配感到惊讶。
For Copy
types you'll likely need 4 impls to be able to add both values to references and references to values, as follows:对于Copy
类型,您可能需要 4 个 impl 才能将值添加到引用和对值的引用,如下所示:
impl std::ops::Add<T> for T;
impl<'a> std::ops::Add<T> for &'a T;
impl<'a> std::ops::Add<&'a T> for T;
impl<'a, 'b> std::ops::Add<&'a T> for &'b T; // Not sure if two lifetimes are needed here, but shouldn't hurt
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.