【发布时间】:2021-03-07 05:34:52
【问题描述】:
我的情况是,我希望一些对象实现一个特征,比如“Base”,而其他一些对象将实现一个特征“Super”。 Super trait 也必须对T : Base 是通用的,这样我就可以根据它所专门使用的 Base 自动实现 Super 的某些部分。现在这似乎适用于以下简单示例
trait Base {
fn say_hi() -> &'static str;
}
struct BaseOne {}
struct BaseTwo {}
impl Base for BaseOne {
fn say_hi() -> &'static str {
"hi!"
}
}
impl Base for BaseTwo {
fn say_hi() -> &'static str {
"hello!"
}
}
trait Super<T: Base> {
fn say_hi(&self) -> &'static str {
T::say_hi()
}
}
struct SuperOne;
struct SuperTwo;
impl Super<BaseOne> for SuperOne {}
impl Super<BaseTwo> for SuperTwo {}
我的问题来自我的下一个要求,即我希望能够存储实现 Super 的对象向量,而不管它专门用于哪个 Base。我的想法是创建一个涵盖所有 Supers 的特征,例如下面的 AnySuper 特征
trait AnySuper {
fn say_hi(&self) -> &'static str;
}
impl<T> AnySuper for dyn Super<T> where T : Base {
fn say_hi(&self) -> &'static str {
Super::say_hi(self)
}
}
然后存储一个 Box 的向量,如下例所示
fn main() {
let one = Box::new(SuperOne);
let two = Box::new(SuperTwo);
let my_vec: Vec<Box<dyn AnySuper>> = Vec::new();
my_vec.push(one);
my_vec.push(two);
}
但不幸的是,失败并出现以下错误
error[E0277]: the trait bound `SuperOne: AnySuper` is not satisfied
--> src/main.rs:52:17
|
52 | my_vec.push(one);
| ^^^ the trait `AnySuper` is not implemented for `SuperOne`
|
= note: required for the cast to the object type `dyn AnySuper`
error[E0277]: the trait bound `SuperTwo: AnySuper` is not satisfied
--> src/main.rs:53:17
|
53 | my_vec.push(two);
| ^^^ the trait `AnySuper` is not implemented for `SuperTwo`
|
= note: required for the cast to the object type `dyn AnySuper`
这有点奇怪,因为在我看来,我已经为所有 Super<T> 实现了 AnySuper。所以我的问题是,我是在做一些根本错误的事情还是只是我的语法有问题?
附:如果有人想玩,我已经在https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a54e3e9044f1edaeb24d8ad934eaf7ec 建立了一个带有此代码的游乐场。
【问题讨论】:
标签: rust