[英]How can a function require that a type implement a trait without removing the existing trait bound?
[英]Implement trait for type with nested bound
我正在尝试为实现泛型特征的类型实现特征,并在内部类型上绑定。 编译器显示了一个错误。 是否有任何已知的解决方法?
trait MyTrait1 {}
trait MyTrait2 {}
trait MyTrait3<T> {}
impl <T: MyTrait1, U: MyTrait3<T>> MyTrait2 for Vec<U> {}
error[E0207]: the type parameter `T` is not constrained by the impl trait, self type, or predicates
--> src/lib.rs:5:7
|
5 | impl <T: MyTrait1, U: MyTrait3<T>> MyTrait2 for Vec<U> {}
| ^ unconstrained type parameter
For more information about this error, try `rustc --explain E0207`.
error: could not compile `playground` due to previous error
不太确定您要做什么,但正如@Sven Marnach 所说,您可以使用关联类型。 这样它就不会不受约束,因为只有一种类型可以与 trait 实现相关联。
trait MyTrait1 {}
trait MyTrait2 {}
trait MyTrait3 {
type AssociatedType;
}
impl<T, U> MyTrait2 for Vec<U>
where
U: MyTrait3<AssociatedType = T>,
T: MyTrait1,
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.