无法为实现我拥有的特征的所有类型实现我不拥有的特征 [英] Can't implement a trait I don't own for all types that implement a trait I do own
问题描述
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]
}
}
}
上述代码产生以下编译时错误:
The preceding code produces the following compile-time error:
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 {
| ^
根据这里提到的实现traits的限制,我应该能够为 AllValues
实现 Rand
,因为 AllValues
是在我的箱子中定义的.一致性/孤儿impl
的规则实际上允许这样做吗?如果是这样,为实现 AllValues
的事物实现 Rand
的正确方法是什么?
According to the restrictions on implementing traits mentioned here I should be able to implement Rand
for AllValues
since AllValues
is defined in my crate. Is this actually allowed by the coherence/orphan impl
s rules? And if so, what is the right way to implement Rand
for things that implement AllValues
?
推荐答案
我应该能够为
AllValues
实现Rand
,因为AllValues
是在我的 crate 中定义的.
I should be able to implement
Rand
forAllValues
sinceAllValues
is defined in my crate.
不,您只能为未定义的类型实现自己的特征 AllValues
.你不能从逻辑上跳到实现一个你也没有定义的无关特征.
No, you are only allowed to implement your own trait AllValues
for types you didn't define. You can't make the logical jump to implementing an unrelated trait that you also didn't define.
有两个注意事项需要记住:
There are two considerations to remember:
- 如果您的 trait 是公开的(它基于您提供的代码),那么您并不是唯一可以实现该 trait 的人.您的 crate 的使用者可能能够为他们自己的类型实现它,他们也可能决定在其中实现
Rand
! - rand crate 可能会决定在未来某个时候为
T
实现Rand
.
- If your trait is public (which it is based on the code you've provided), you aren't the only one that can implement the trait. Consumers of your crate might be able to implement it for their own types, where they might also decide to implement
Rand
! - The rand crate might decide to implement
Rand
forT
some time in the future.
为实现 AllValues
的事物实现 Rand
的正确方法是什么?
What is the right way to implement
Rand
for things that implementAllValues
?
我不相信有.我只是引入了一个包装器类型,它保存一个值或一个值的引用,该值实现了你的 trait 并为此实现了 Rand
.
I don't believe there is one. I'd just introduce a wrapper type that holds a value or a reference to a value that implements your trait and implement Rand
for that.
另见:
这篇关于无法为实现我拥有的特征的所有类型实现我不拥有的特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!