如何在不消耗价值的情况下实现添加特征 [英] How to implement Add trait without consuming the value
本文介绍了如何在不消耗价值的情况下实现添加特征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在实现Add
特征时(以及其他一些特征,如Mul
、Sub
等)对于简单结构,必须完全使用结构值,因此不可能在以后使用它。
u8
、usize
等)实现Add
,同时允许在调用add
之后使用它。
如何实现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)]
添加到结构中,然后它将使用一个副本,而不是使用该值。
这篇关于如何在不消耗价值的情况下实现添加特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文