我有一個特徵Trait
與關聯的類型Trait::Associated
。我通過要求,這是由它的相關類型的可轉位,如下所示試圖綁定的特點:使用特徵的相關類型作爲參數綁定的特徵
use std::ops::Index;
pub trait Trait: Index<Trait::Associated> {
type Associated;
}
然而,編譯器抱怨說,相關類型是不明確的
error: ambiguous associated type; specify the type using the syntax
<Type as Trait>::Associated
[E0223]
pub trait Trait: Index<Trait::Associated> ^~~~~~~~~~~~~~~~~
我也嘗試過參考相關類型Self::Associated
,但可以理解的是編譯器抗議類型和特徵之間的循環引用。
最後,我也想明確地實施Index
爲Trait
:
pub trait Trait {
type Associated;
}
impl<T: Trait> Index<T::Associated> for T {
type Output = str;
fn index(&self, associated: T::Associated) -> &'static str { "sup" }
}
不幸失敗過:
error: type parameter
T
must be used as the type parameter for some local type (e.g.MyStruct<T>
); only traits defined in the current crate can be implemented for a type parameter
我是不是想在這裏做什麼不合理?有沒有辦法實現類似的東西,而不必使用泛型?
謝謝,這工作完美!順便提一句,有沒有辦法讓我的第三次嘗試工作(特質定義和「impl」塊是分開的)?如果我嘗試在'impl'行中使用'Self',rustc會抱怨。 – Jean
@Jean:語法應該是'impl索引< :: T>的相關>,但這裏存在一致性問題。你不僅可以從另一個箱子中爲自己的箱子類型實現一個「特質」(以避免多人提供給定類型的給定特質的衝突實現)。在這裏,「T」不限於你的箱子的類型......所以它是被禁止的。 –