0

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:

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 outputs rustc 1.36.0 (a53f9df32 2019-07-03)
  • cargo -V outputs cargo 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?

Peter Hall
  • 53,120
  • 14
  • 139
  • 204
OMGtechy
  • 7,935
  • 8
  • 48
  • 83
  • Possible duplicate of [How to use one module from another module in a Rust cargo project?](https://stackoverflow.com/questions/48071513/how-to-use-one-module-from-another-module-in-a-rust-cargo-project) – edwardw Aug 24 '19 at 16:52

1 Answers1

3

You have declared the module my_trait twice, so there are actually two different traits called MyTrait: crate::my_trait and crate::my_struct::my_trait.

You don't need to declare the module in the my_struct module. Instead, use the module that is declared in the crate root, with:

use crate::my_trait::MyTrait;

Or

use super::my_trait::MyTrait;
Peter Hall
  • 53,120
  • 14
  • 139
  • 204