rust - 为什么 std::ops:Mul 不需要限制输出类型?
问题描述
为了编译下面的代码,我必须指定 Add 操作的输出类型。但是,使用 Mul 操作的非常相似的代码不需要此规范。为什么这里的 Add 和 Mul 操作有区别?
trait IdentityExt {
fn identity(self) -> Self;
}
impl<T> IdentityExt for T where T: std::ops::Mul, T: num::One {
fn identity(self) -> T {
self * T::one()
}
}
trait IncrementExt {
fn increment(self) -> Self;
}
//impl<T> IncrementExt for T where T: std::ops::Add, T: num::One { // Doesn't compile
impl<T> IncrementExt for T where T: std::ops::Add<Output = T>, T: num::One {
fn increment(self) -> T {
self + T::one()
}
}
fn main() {
let x = 13;
println!("{:?}", x.increment());
println!("{:?}", x.identity());
}
解决方案
因为One
trait 已经做到了,pub trait One: Mul<Self, Output = Self>
. 所以,你可以只写impl<T> IdentityExt for T where T: num::One {
.
他们添加它是因为他们希望 One 跟随:
a * 1 = a ∀ a ∈ Self
1 * a = a ∀ a ∈ Self