代码
pub trait Q<S> {
fn f();
}
pub trait A {
type I;
type F: Q<Self::I>;
}
// this works (1)
//
// pub struct S<T>
// where
// T: A
// {
// unsatisfied trait bound (2)
pub struct S<T>
where
T: A<I = bool>,
{
t: T,
}
编译失败:
error[E0277]: the trait bound `<T as A>::F: Q<bool>` is not satisfied
--> src/main.rs:18:1
|
18 | / pub struct S<T>
19 | | where
20 | | T: A<I = bool>,
21 | | {
22 | | t: T,
23 | | }
| |_^ the trait `Q<bool>` is not implemented for `<T as A>::F`
|
= help: consider adding a `where <T as A>::F: Q<bool>` bound
= note: required by `A`
有趣的是,如果你使用注释掉的第一行(1)而不是第二行(2),它也可以工作。如果你把相关类型I
变成一个泛型类型(写trait A<I>
和A<bool>
),它也可以工作。
impl<T> S<T>
where T: A
{
fn g() {
T::F::f()
}
}
如果在第一行或泛型类型 I
中成功,那么在这些情况下确实假定了 T::F : Q<bool>
。
为什么会自动假定具有第一行或泛型类型的特质边界,但不假定第二行呢?
我们能否在使用 T: A<I=bool>
时修复上述代码,而无需每次附加 where T::F: Q<bool>
?