2

为什么这段代码编译失败?操场

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不是预期的。如果我删除函数中的 where 子句,则此代码有效value

4

0 回答 0