I am writing projects in Rust to help me learn it, but am having trouble implementing a trait and then using a function required by that trait when a type implementing it is passed to a function.
To try and narrow down the problem, I've created an MVCE. Here is the error message and code:
error message
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 { });
}
My attempts at researching the problem mostly found people trying to implement fairly standard Rust traits, for example:
- How can I implement Rust's Copy trait?
- The trait bound is not satisfied in Rust
- The trait bound is not satisfied
I also read somewhere that I needed to reimplement the trait for variables such as &MyStruct
, but my attempts to do so didn't resolve the issue.
extra info
rustc -V
outputsrustc 1.36.0 (a53f9df32 2019-07-03)
cargo -V
outputscargo 1.36.0 (c4fcfb725 2019-05-15)
- Platform/OS is Windows 10 Pro (x86_64)
question
What am I doing wrong; how can I correctly implement the trait?