MST

星途 面试题库

面试题:Rust结构体一元运算符重载中的泛型与trait约束

定义一个泛型结构体`NumericWrapper<T>`,其中`T`可以是任何实现了`Copy`和`Neg` trait的类型。重载一元负号运算符`-`,使得对`NumericWrapper<T>`实例使用负号时,返回一个新的`NumericWrapper<T>`实例,其内部值为原实例内部值取负。同时要确保在编译时,如果`T`类型没有实现`Copy`和`Neg` trait,编译器能够给出恰当的错误提示。
26.0万 热度难度
编程语言Rust

知识考点

AI 面试

面试题答案

一键面试
struct NumericWrapper<T>
where
    T: Copy + std::ops::Neg<Output = T>,
{
    value: T,
}

impl<T> std::ops::Neg for NumericWrapper<T>
where
    T: Copy + std::ops::Neg<Output = T>,
{
    type Output = NumericWrapper<T>;

    fn neg(self) -> Self::Output {
        NumericWrapper {
            value: -self.value,
        }
    }
}