rust - 如何在不消耗值的情况下实现添加特征

标签 rust traits

实现 Add 时对于一个简单的结构,我们必须完全消耗该结构值,因此它的后续使用是不可能的。

同时,内置原语( MulSub 等)实现 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/

相关文章:

macros - 如何在宏中包含唯一匹配案例的文档?

rust - "borrowed value does not live long enough"好像怪错了

C++ - 知道类型/类是否嵌套?

c++ - 声明用于日志记录的类的模块名称

rust - 如何在 Rust 中编写一个循环来打印 0 到 99 之间的数字?

rust - 将 `&str` 附加到 `String` 的最有效方法是什么?

Rust libp2p 在 crate libp2p 中找不到函数development_transport

traits - Kotlin:无法从 trait 访问父类(super class)

rust - 只有当 impl 标记为 `default` 时关联类型和类型参数不匹配

methods - 如何在 Rust 中使用方法作为函数指针