类型不匹配从特征中的泛型函数返回关联特征

时间:2020-08-31 15:23:59

标签: rust

为什么此代码无法编译? 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()
    }
}

此错误:

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`

错误指向第18行,该行的关联类型设置为String,但是这表示未预期到String。如果删除value函数中的where子句,则此代码有效。

0 个答案:

没有答案