实现 Add
时对于一个简单的结构,我们必须完全消耗该结构值,因此它的后续使用是不可能的。
同时,内置原语( Mul
、 Sub
等)实现 u8
同时允许在 usize
之后使用它被叫了。
我该如何实现Add
让我的结构能够在调用 add
后使用它?
use std::ops::Add;
struct I(usize);
impl Add for I {
type Output = Self;
fn add(self, rhs: Self) -> Self {
I(self.0 + rhs.0)
}
}
fn main() {
let a = 123;
let b = a + a; // no error
let a1 = I(123);
let b1 = a1 + a1;
println!("b={}", b);
}
error[E0382]: use of moved value: `a1`
--> src/main.rs:16:19
|
15 | let a1 = I(123);
| -- move occurs because `a1` has type `I`, which does not implement the `Copy` trait
16 | let b1 = a1 + a1;
| -- ^^ value used here after move
| |
| value moved here
最佳答案
您应该能够将 #[derive(Copy, Clone)]
添加到结构中,然后它将消耗一个副本,而不是消耗该值。
关于rust - 如何在不消耗值的情况下实现添加特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57294038/