Подумайте о каждом из методов, которые нужно связать с Trait
, а не с самим объектом. Посмотрите на этот более простой пример:
trait Foo {
fn foo(&self) -> &'static str;
}
trait FooPrime {
fn foo(&self) -> &'static str;
}
struct Bar {}
impl Foo for Bar {
fn foo(&self) -> &'static str {
"foo"
}
}
impl FooPrime for Bar {
fn foo(&self) -> &'static str {
"foo prime"
}
}
fn main() {
let bar = Bar{};
println!("{} : {}", bar.foo(), bar.foo());
}
При компиляции мы получаем следующую ошибку:
Compiling playground v0.0.1 (/playground)
error[E0034]: multiple applicable items in scope
--> src/main.rs:25:29
|
25 | println!("{} : {}", bar.foo(), bar.foo());
| ^^^ multiple `foo` found
|
note: candidate #1 is defined in an impl of the trait `Foo` for the type `Bar`
--> src/main.rs:12:5
|
12 | fn foo(&self) -> &'static str {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: candidate #2 is defined in an impl of the trait `FooPrime` for the type `Bar`
--> src/main.rs:18:3
|
18 | fn foo(&self) -> &'static str {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: disambiguate the associated function for candidate #1
|
25 | println!("{} : {}", Foo::foo(&bar), bar.foo());
| ^^^^^^^^^^^^^^
help: disambiguate the associated function for candidate #2
|
25 | println!("{} : {}", FooPrime::foo(&bar), bar.foo());
| ^^^^^^^^^^^^^^^^^^^
error[E0034]: multiple applicable items in scope
--> src/main.rs:25:40
|
25 | println!("{} : {}", bar.foo(), bar.foo());
| ^^^ multiple `foo` found
|
note: candidate #1 is defined in an impl of the trait `Foo` for the type `Bar`
--> src/main.rs:12:5
|
12 | fn foo(&self) -> &'static str {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
note: candidate #2 is defined in an impl of the trait `FooPrime` for the type `Bar`
--> src/main.rs:18:3
|
18 | fn foo(&self) -> &'static str {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: disambiguate the associated function for candidate #1
|
25 | println!("{} : {}", bar.foo(), Foo::foo(&bar));
| ^^^^^^^^^^^^^^
help: disambiguate the associated function for candidate #2
|
25 | println!("{} : {}", bar.foo(), FooPrime::foo(&bar));
Нам нужно явно указать компилятору, какой метод использовать :
fn main() {
let bar = Bar{};
println!("{} : {}", Foo::foo(&bar), FooPrime::foo(&bar));
}
Площадка
По той же причине в вашем коде не используется метод для другого признака, поскольку он не является частью предыдущего признака. Вот ссылка на книгу
Возможно, вы захотите использовать функцию supertrait для создания импликации по умолчанию для другой черты на основе «родительской»:
trait FooPrime : Foo {
fn foo(&self) -> &'static str {
Foo::foo(self)
}
}
Детская площадка