gpt4 book ai didi

rust - 无法为实现我拥有的特征的所有类型实现我不拥有的特征

转载 作者:行者123 更新时间:2023-11-29 08:31:11 24 4
gpt4 key购买 nike

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我应该能够为 AllValues 实现 Rand,因为 AllValues 是在我的 crate 中定义的。 coherence/orphan impl 规则实际上允许这样做吗?如果是这样,那么为实现 AllValues 的事物实现 Rand 的正确方法是什么?

最佳答案

I should be able to implement Rand for AllValues since AllValues is defined in my crate.

不,您只能为您未定义的类型实现您自己的特征AllValues。您无法从逻辑上跳转到实现您也未定义的不相关特征。

有两个注意事项需要记住:

  • 如果您的特征是公开的(它基于您提供的代码),那么您不是唯一可以实现该特征的人。您的箱子的消费者可能能够为他们自己的类型实现它,他们也可能决定实现 Rand!
  • rand crate 可能决定在未来某个时间为T 实现Rand

What is the right way to implement Rand for things that implement AllValues?

我不相信有一个。我只是介绍一个包装器类型,它包含一个值或对实现您的特征的值的引用,并为此实现 Rand

另见:

关于rust - 无法为实现我拥有的特征的所有类型实现我不拥有的特征,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57406658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com