Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Rust: "the trait is not implemented for Self" even though it totally is

Look at this little snippet:

pub trait TestTrait {
    fn test_function(&self) {
        generic_function(self);
    }   
}

fn generic_function<T : TestTrait> (x : T) {
    //do something
}

This produces this error message:

error[E0277]: the trait bound `&Self: TestTrait` is not satisfied
  --> src\main.rs:10:26
   |
10 |         generic_function(self);
   |         ---------------- ^^^^ the trait `TestTrait` is not implemented for `&Self`
   |         |
   |         required by a bound introduced by this call
   |
note: required by a bound in `generic_function`
  --> src\main.rs:14:25
   |
14 | fn generic_function<T : TestTrait> (x : T) {
   |                         ^^^^^^^^^ required by this bound in `generic_function`

But this doesn’t make any sense. The test function is a method associated with the trait TestTrait. Of course, the self is going to implement this trait, that’s the entire point!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What’s going on? How to make this work?

>Solution :

generic_function takes an object by value. The function generic_function gets a reference to self and does not own self so is not able to give self by value to generic_function.

There are 2 simple fixes. Note that both require the constrain TestTrait where Self: Sized.

1: generic_function takes the argument by reference

pub trait TestTrait where Self: Sized {
    fn test_function(&self) {
        generic_function(self);
    }   
}

fn generic_function<T : TestTrait> (x : &T) {
    //do something
}
  1. test_function takes self by value
pub trait TestTrait where Self: Sized {
    fn test_function(self) {
        generic_function(self);
    }   
}

fn generic_function<T : TestTrait> (x : T) {
    //do something
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading