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

Viewed 438

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!

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

1 Answers

generic_function takes an object by value. The function test_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 constraint 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
}
Related