Rust 中的通用函数调用语法(Generic Function Call Syntax)允许你调用实现了特定 trait 的方法,而不管具体类型是什么。这个语法使用 <T as Trait>::method 的形式,其中 T 是具体类型,Trait 是要调用的 trait,method 是 trait 中的方法。

以下是一个简单的例子,假设有一个 trait 叫做 Print:
trait Print {
    fn print(&self);
}

struct Circle {
    radius: f64,
}

impl Print for Circle {
    fn print(&self) {
        println!("Printing Circle with radius: {}", self.radius);
    }
}

struct Rectangle {
    width: f64,
    height: f64,
}

impl Print for Rectangle {
    fn print(&self) {
        println!("Printing Rectangle with width: {} and height: {}", self.width, self.height);
    }
}

现在,你可以使用通用函数调用语法调用 Print trait 中的方法:
fn main() {
    let circle = Circle { radius: 5.0 };
    let rectangle = Rectangle { width: 4.0, height: 6.0 };

    call_print(&circle);
    call_print(&rectangle);
}

fn call_print<T: Print>(shape: &T) {
    T::print(shape);
}

在这个例子中,call_print 函数接受实现了 Print trait 的任何类型,并通过通用函数调用语法调用 Print trait 中的 print 方法。

注意,在具体的情况下,通常更倾向于使用 impl Trait 语法,这样代码会更简洁:
fn call_print(shape: &impl Print) {
    shape.print();
}

这是通用函数调用语法的基本概念。它允许你在不同类型上调用相同 trait 中的方法,提高了代码的灵活性。


转载请注明出处:http://www.pingtaimeng.com/article/detail/6806/Rust