尝试实现超特征中声明的函数时出错
Error when trying to implement a function declared in a supertrait
我正在尝试实现具有超级特征的特征,如下所示:
trait A {
fn do_a(&self);
}
trait B: A {
fn do_b(&self);
}
struct S {}
impl B for S {
fn do_a(&self) {}
fn do_b(&self) {}
}
当我 运行 cargo build 时,我得到了这些编译器错误:
error[E0407]: method `do_a` is not a member of trait `B`
--> src/example.rs:12:5
|
12 | fn do_a(&self) {}
| ^^^^^^^^^^^^^^^^^ not a member of trait `B`
error[E0277]: the trait bound `example::S: example::A` is not satisfied
--> src/example.rs:11:6
|
5 | trait B: A {
| - required by this bound in `example::B`
...
11 | impl B for S {
| ^ the trait `example::A` is not implemented for `example::S`
我一直在重新阅读有关超级特征的内容,但我无法理解这个错误。
- 第一个错误似乎与
trait B: A
告诉程序要做的事情相矛盾。
- 第二个错误似乎与
do_a(&self) {}
的实现满足A
相矛盾。
我在这里错过了什么?是我的心智模型有误,还是我的代码缺少一些必要的样板文件,或两者兼而有之?
我认为语法更多的是关于类型的限制(例如实现 B
的类型 T
必须 必须实现 A
) 而不是面向对象意义上的继承。如果你单独写出 impl
s,它编译得很好:
trait A {
fn do_a(&self);
}
trait B: A {
fn do_b(&self);
}
struct S {}
impl A for S {
fn do_a(&self) {}
}
impl B for S {
fn do_b(&self) {}
}
N.B。如果您删除 A
的 impl
代码将不再编译,则不再满足 B
的 impl
也必须 impl A
的约束。
我正在尝试实现具有超级特征的特征,如下所示:
trait A {
fn do_a(&self);
}
trait B: A {
fn do_b(&self);
}
struct S {}
impl B for S {
fn do_a(&self) {}
fn do_b(&self) {}
}
当我 运行 cargo build 时,我得到了这些编译器错误:
error[E0407]: method `do_a` is not a member of trait `B`
--> src/example.rs:12:5
|
12 | fn do_a(&self) {}
| ^^^^^^^^^^^^^^^^^ not a member of trait `B`
error[E0277]: the trait bound `example::S: example::A` is not satisfied
--> src/example.rs:11:6
|
5 | trait B: A {
| - required by this bound in `example::B`
...
11 | impl B for S {
| ^ the trait `example::A` is not implemented for `example::S`
我一直在重新阅读有关超级特征的内容,但我无法理解这个错误。
- 第一个错误似乎与
trait B: A
告诉程序要做的事情相矛盾。 - 第二个错误似乎与
do_a(&self) {}
的实现满足A
相矛盾。
我在这里错过了什么?是我的心智模型有误,还是我的代码缺少一些必要的样板文件,或两者兼而有之?
我认为语法更多的是关于类型的限制(例如实现 B
的类型 T
必须 必须实现 A
) 而不是面向对象意义上的继承。如果你单独写出 impl
s,它编译得很好:
trait A {
fn do_a(&self);
}
trait B: A {
fn do_b(&self);
}
struct S {}
impl A for S {
fn do_a(&self) {}
}
impl B for S {
fn do_b(&self) {}
}
N.B。如果您删除 A
的 impl
代码将不再编译,则不再满足 B
的 impl
也必须 impl A
的约束。