简体   繁体   English

为具有嵌套边界的类型实现特征

[英]Implement trait for type with nested bound

I'm trying to implement a trait for a type implementing a generic trait with a bound on the inner type.我正在尝试为实现泛型特征的类型实现特征,并在内部类型上绑定。 The compiler shows me an error.编译器显示了一个错误。 Are there any known workarounds for this?是否有任何已知的解决方法?

Code代码

trait MyTrait1 {}
trait MyTrait2 {}
trait MyTrait3<T> {}

impl <T: MyTrait1, U: MyTrait3<T>> MyTrait2 for Vec<U> {}

Playground 操场

Error:错误:

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

Not quite sure what you are trying to do but as @Sven Marnach said you can use associated types.不太确定您要做什么,但正如@Sven Marnach 所说,您可以使用关联类型。 That way it will not be unconstrained because only one type can be associated with the trait implementation.这样它就不会不受约束,因为只有一种类型可以与 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM