Fully Qualified Syntax
完全限定语法(fully qualified syntax) 是 rust 中调用函数的最完整、无歧义的方式,例子:
trait Foo {
fn bar() -> String;
}
struct Apple;
impl Foo for Apple {
fn bar() -> String {
String::from("apple")
}
}
fn main() {
println!("{}", <Apple as Foo>::bar());
}
主要用于调用同名关联函数的场景:
trait Animal {
fn baby_name() -> String;
}
struct Dog;
impl Dog {
fn baby_name() -> String {
String::from("Spot")
}
}
impl Animal for Dog {
fn baby_name() -> String {
String::from("puppy")
}
}
此时调用 Dog::baby_name()
会得到 "Spot"
的结果,若想要得到 "puppy"
,就必须使用 完全限定语法。
如果同名的是方法,还可以通过:
trait Pilot {
fn fly(&self);
}
trait Wizard {
fn fly(&self);
}
struct Human;
impl Pilot for Human {
fn fly(&self) {
println!("This is your captain speaking.");
}
}
impl Wizard for Human {
fn fly(&self) {
println!("Up!");
}
}
impl Human {
fn fly(&self) {
println!("*waving arms furiously*");
}
}
fn main() {
let person = Human;
Pilot::fly(&person);
Wizard::fly(&person);
person.fly();
}
来指定不同 trait 的方法。
Why we need fully qualified syntax?
Nothing in Rust prevents a trait from having a method with the same name as another trait’s method, nor does Rust prevent you from implementing both traits on one type. It’s also possible to implement a method directly on the type with the same name as methods from traits.
When calling methods with the same name, you’ll need to tell Rust which one you want to use.[1]