MST
星途 面试题库

面试题:Rust特征中泛型的复杂约束

编写一个Rust特征 `MathOp`,它有两个泛型参数 `T` 和 `U`,并且有一个方法 `operate`,该方法要求 `T` 和 `U` 都实现 `std::fmt::Display` 特征,`operate` 方法将 `T` 和 `U` 进行某种运算(例如加法,假设 `T` 和 `U` 都实现了 `Add` 特征),并返回运算结果,同时结果类型也需要实现 `std::fmt::Display` 特征。然后创建两个合适的结构体实现这个特征。
46.3万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
use std::fmt::Display;

// 定义特征
trait MathOp<T, U> {
    fn operate(&self, a: T, b: U) -> impl Display
    where
        T: Display + std::ops::Add<U, Output = T>,
        U: Display;
}

// 定义结构体
struct Adder;

// 实现特征
impl MathOp<i32, i32> for Adder {
    fn operate(&self, a: i32, b: i32) -> impl Display {
        a + b
    }
}

struct FloatAdder;

impl MathOp<f64, f64> for FloatAdder {
    fn operate(&self, a: f64, b: f64) -> impl Display {
        a + b
    }
}