以下是一个简单的例子,假设有一个 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