面试题答案
一键面试// 定义自定义特征 MathOperation
trait MathOperation {
type Output;
fn operate(&self, a: Self::Input, b: Self::Input) -> Self::Output;
}
// 为 i32 类型实现 MathOperation 特征
struct Add;
impl MathOperation for Add {
type Output = i32;
fn operate(&self, a: i32, b: i32) -> i32 {
a + b
}
}
// 定义泛型函数 perform_operation
fn perform_operation<T: MathOperation>(op: &T, a: T::Input, b: T::Input) -> T::Output {
op.operate(a, b)
}
你可以这样调用:
fn main() {
let add_op = Add;
let result = perform_operation(&add_op, 5, 3);
println!("The result is: {}", result);
}