MST

星途 面试题库

面试题:Rust函数指针与泛型和trait的深度结合

定义一个trait `MathOperation`,它包含一个方法`operate`,接受两个泛型参数并返回一个泛型结果。然后,编写一个函数`apply_operation`,它接受一个实现了`MathOperation` trait的类型的实例以及两个泛型参数。在`apply_operation`函数内部,使用函数指针来调用`operate`方法。接着,定义两个结构体,分别实现`MathOperation` trait,一个结构体实现加法操作,另一个实现乘法操作。最后,在`main`函数中展示如何使用`apply_operation`函数对不同类型的数据(例如`i32`和`f64`)应用这两种不同的操作。
33.9万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
// 定义trait
trait MathOperation<T> {
    fn operate(&self, a: T, b: T) -> T;
}

// 使用函数指针调用operate方法
fn apply_operation<T, F>(op: &F, a: T, b: T) -> T
where
    F: MathOperation<T>,
{
    (op.operate)(a, b)
}

// 加法结构体
struct Add;

impl<T: std::ops::Add<Output = T>> MathOperation<T> for Add {
    fn operate(&self, a: T, b: T) -> T {
        a + b
    }
}

// 乘法结构体
struct Multiply;

impl<T: std::ops::Mul<Output = T>> MathOperation<T> for Multiply {
    fn operate(&self, a: T, b: T) -> T {
        a * b
    }
}

fn main() {
    let add = Add;
    let multiply = Multiply;

    // 对i32类型应用操作
    let result_i32_add = apply_operation(&add, 5i32, 3i32);
    let result_i32_multiply = apply_operation(&multiply, 5i32, 3i32);
    println!("i32加法结果: {}", result_i32_add);
    println!("i32乘法结果: {}", result_i32_multiply);

    // 对f64类型应用操作
    let result_f64_add = apply_operation(&add, 5.0f64, 3.0f64);
    let result_f64_multiply = apply_operation(&multiply, 5.0f64, 3.0f64);
    println!("f64加法结果: {}", result_f64_add);
    println!("f64乘法结果: {}", result_f64_multiply);
}