pub trait AllValues {
fn all_values() -> Vec<Self> where Self: std::marker::Sized;
}
use rand::Rand;
use rand::Rng;
impl<T: AllValues + Sized> Rand for T {
fn rand<R: Rng, T>(rng: &mut R) -> T {
let values = T::all_values();
let len = values.len();
if len == 0 {
panic!("Cannot pick a random value because T::all_values() returned an empty vector!")
} else {
let i = rng.gen_range(0, len);
values[i]
}
}
}
前面的代碼生成以下編譯時錯誤:不能實現一個特點,我不爲自己實現一個特質各類我自己
error[E0210]: 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
--> src/lib.rs:137:1
|
137 | impl<T: AllValues + Sized> Rand for T {
|^
據有關限制實現提到的特性here我應該能夠實現Rand
的AllValues
因爲我的箱子中定義了AllValues
。這實際上是否符合連貫性/孤兒impl
的規則?如果是這樣,那麼實施AllValues
的東西實施Rand
的正確方法是什麼?
我認爲這個實例將不得不被定義在哪裏'Rand'是...... – Alec