如何在 Rust 中指定结构体字段必须实现某个 trait?
大家好!我最近在写 Rust,遇到了一个关于 trait 的问题。我想创建一个结构体,它存储某个值,并且这个值必须实现特定的 trait。例如,我正在写一个简单的计算器,其中有一个 `Operation` trait 和 `compute` 方法。我希望 `Calculator` 结构体有一个 `operation` 字段,它可以是任何实现了这个 trait 的结构体。
以下是我尝试做的:
```rust
trait Operation {
fn compute(&self, a: i32, b: i32) -> i32;
}
struct Calculator {
operation: Operation, // 错误:trait objects must include the `dyn` keyword
}
fn main() {
let add = AddOperation;
let calc = Calculator { operation: add };
println!("{}", calc.operation.compute(5, 3));
}
```
编译器报错:"the trait `Operation` cannot be made into an object"。我读过关于 `dyn` 和 `Box` 的内容,但不知道哪种方法正确。是否需要使用 `Box`,或者有其他方式?