在学习如何扩展特质的同时,我遇到了一个问题。我试图为子特性实现超特性,为结构实现子特性。我希望该结构可以从上级特征和子级特征中调用方法/关联函数,就像OOP继承一样:
trait FunctionA {
fn print_username(&self) {
println!("username");
}
}
trait FunctionB {
fn print_number(&self) {
println!("number");
}
}
impl FunctionA for FunctionB {}
struct Demo {}
impl FunctionB for Demo {}
fn main() {
let demo = Demo {};
demo.print_user_name();
demo.print_number();
}
编译器显示错误:
error[E0599]: no method named `print_user_name` found for type `Demo` in the current scope
--> src/main.rs:21:10
|
15 | struct Demo {}
| ----------- method `print_user_name` not found for this
...
21 | demo.print_user_name();
| ^^^^^^^^^^^^^^^
我是否对扩展性格有任何误解?是我试图禁止的吗?如果允许,如何正确实施?