簡體   English   中英

為具有嵌套邊界的類型實現特征

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM