【发布时间】:2019-12-29 13:30:05
【问题描述】:
我正在用 Rust 编写项目来帮助我学习它,但是在实现一个 trait 并且在将实现它的类型传递给函数时使用该 trait 所需的函数时遇到了麻烦。
为了尝试缩小问题范围,我创建了一个MVCE。以下是错误信息和代码:
错误信息
error[E0277]: the trait bound `my_struct::MyStruct: my_trait::MyTrait` is not satisfied
--> src\main.rs:12:5
|
12 | invoke_print_i32(&MyStruct { });
| ^^^^^^^^^^^^^^^^ the trait `my_trait::MyTrait` is not implemented for `my_struct::MyStruct`
|
note: required by `invoke_print_i32`
--> src\main.rs:7:1
|
7 | fn invoke_print_i32<T: MyTrait>(instance: &T) {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
my_trait.rs
pub trait MyTrait {
fn print_i32(&self, n: i32);
}
my_struct.rs
#[path = "my_trait.rs"]
mod my_trait;
use my_trait::MyTrait;
pub struct MyStruct { }
impl MyTrait for MyStruct {
fn print_i32(&self, n: i32) {
println!("n: {}", n);
}
}
main.rs
mod my_trait;
use my_trait::MyTrait;
mod my_struct;
use my_struct::MyStruct;
fn invoke_print_i32<T: MyTrait>(instance: &T) {
instance.print_i32(42);
}
fn main() {
invoke_print_i32(&MyStruct { });
}
我研究这个问题的尝试主要是发现人们试图实现相当标准的 Rust 特征,例如:
- How can I implement Rust's Copy trait?
- The trait bound is not satisfied in Rust
- The trait bound is not satisfied
我还在某处读到我需要为 &MyStruct 等变量重新实现特征,但我尝试这样做并没有解决问题。
额外信息
-
rustc -V输出rustc 1.36.0 (a53f9df32 2019-07-03) -
cargo -V输出cargo 1.36.0 (c4fcfb725 2019-05-15) - 平台/操作系统为 Windows 10 Pro (x86_64)
问题
我做错了什么;如何正确实现 trait?
【问题讨论】: