Type mismatch returning associated trait from generic function in trait

Viewed 65

Why does this code fail to compile? Playground

pub trait Dataset {}

pub trait Property {
    type Value;
    fn value<D: Dataset>(_ds: D) -> Self::Value
    where
        Self: DatasetProperty<D>;
}

pub trait DatasetProperty<D>
where
    Self: Property,
    D: Dataset,
{
}

impl<T> Property for T {
    type Value = String;
    fn value<D: Dataset>(_ds: D) -> Self::Value
    where
        Self: DatasetProperty<D>,
    {
        String::new()
    }
}

This errors with:

error[E0308]: mismatched types
  --> src/lib.rs:23:9
   |
18 |     type Value = String;
   |     -------------------- expected this associated type
19 |     fn value<D: Dataset>(_ds: D) -> Self::Value
   |                                     ----------- expected `<T as Property>::Value` because of return type
...
23 |         String::new()
   |         ^^^^^^^^^^^^^ expected associated type, found struct `std::string::String`
   |
   = note: expected associated type `<T as Property>::Value`
                       found struct `std::string::String`

The error points to line 18 where the associated type is set to String, but then it's saying String was not expected. This code works if I remove the where clause in the value function.

0 Answers
Related