2016-03-04 59 views
7

我有一個特徵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,但可以理解的是編譯器抗議類型和特徵之間的循環引用。

最後,我也想明確地實施IndexTrait

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

我是不是想在這裏做什麼不合理?有沒有辦法實現類似的東西,而不必使用泛型?

Playpen link

回答

9

你很近,非常接近。

答案很簡單:Trait根本不認爲其定義的任何參考Trait指當前類型,畢竟,你可以不妨參考一下其他類型也實現Trait

爲了指定您想要的特定類型,您應該注意提示:使用<Type as Trait>::Associated,其中Type是當前類型。

因此,在定義Trait時,如何引用它將被實例化的具體類型?您使用Self

的解決方案,從而爲:

pub trait Trait: Index<<Self as Trait>::Associated> { 
    type Associated; 
} 
+0

謝謝,這工作完美!順便提一句,有沒有辦法讓我的第三次嘗試工作(特質定義和「impl」塊是分開的)?如果我嘗試在'impl'行中使用'Self',rustc會抱怨。 – Jean

+1

@Jean:語法應該是'impl 索引< :: T>的相關>,但這裏存在一致性問題。你不僅可以從另一個箱子中爲自己的箱子類型實現一個「特質」(以避免多人提供給定類型的給定特質的衝突實現)。在這裏,「T」不限於你的箱子的類型......所以它是被禁止的。 –

1

我認爲有以下提供你想要的語義,把你的第二次嘗試的方法。

pub trait Trait { 
    type Associated; 
} 

impl<T> Index<T> for Trait<Associated=T> { 
    type Output=str; 
    fn index(&self, associated: T) -> &'static str { "sup" } 
}