Rust 涉及关联类型的未满足特征界限
代码Rust 涉及关联类型的未满足特征界限,rust,traits,Rust,Traits,代码 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>
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,
}
使用第(1)行或泛型类型I
成功,因此在这些情况下确实假定T::F:Q
为什么特征绑定自动假定为第(1)行或泛型类型,而不是第(2)行
我们是否可以在不追加
的情况下修复上述代码,其中T::F:Q
每次使用T:A
?从Rust 1.18开始,编译器要求您编写这些边界,以便类型格式良好。基本上,为了使绑定T:A
保持不变,需要绑定T::F:Q
也保持不变。例如,如果某个类型试图实现A
,如下所示:
struct Y;
struct Z;
impl A for Y {
type I = bool;
type F = Z; // Z does not implement Q<bool>
}
pub trait A
where
Self::F: Q<Self::I>,
{
type I;
type F;
}
对于第(2)行,绑定的T::F:Q
看起来可能只是将T::I
替换为bool
,但这种差异对编译器很重要T::I
是一个关联类型,而bool
是一个具体类型
Rust开发人员正在考虑改进编译器,这样就不必在任何地方重复这样的边界
pub trait A
where
Self::F: Q<Self::I>,
{
type I;
type F;
}