pub trait Mul<Rhs = Self> {
type Output;
// Required method
fn mul(self, rhs: Rhs) -> Self::Output;
}
Expand description
乘法运算符 *
。
请注意,默认情况下 Rhs
是 Self
,但这不是强制性的。
Examples
Mul
tipliable 的有理数
use std::ops::Mul;
// 根据算术的基本定理,最低限度的有理数是唯一的。
// 因此,通过将 `Rational` 保持为简化形式,我们可以得出 `Eq` 和 `PartialEq`。
#[derive(Debug, Eq, PartialEq)]
struct Rational {
numerator: usize,
denominator: usize,
}
impl Rational {
fn new(numerator: usize, denominator: usize) -> Self {
if denominator == 0 {
panic!("Zero is an invalid denominator!");
}
// 用最大公约数除以最低条件。
let gcd = gcd(numerator, denominator);
Self {
numerator: numerator / gcd,
denominator: denominator / gcd,
}
}
}
impl Mul for Rational {
// 有理数的乘法是一个封闭运算。
type Output = Self;
fn mul(self, rhs: Self) -> Self {
let numerator = self.numerator * rhs.numerator;
let denominator = self.denominator * rhs.denominator;
Self::new(numerator, denominator)
}
}
// 欧几里德 (Euclid) 具有 2000 年历史的算法,用于找到最大公约数。
fn gcd(x: usize, y: usize) -> usize {
let mut x = x;
let mut y = y;
while y != 0 {
let t = y;
y = x % y;
x = t;
}
x
}
assert_eq!(Rational::new(1, 2), Rational::new(2, 4));
assert_eq!(Rational::new(2, 3) * Rational::new(3, 4),
Rational::new(1, 2));
Run将 vectors 乘以线性代数中的标量
use std::ops::Mul;
struct Scalar { value: usize }
#[derive(Debug, PartialEq)]
struct Vector { value: Vec<usize> }
impl Mul<Scalar> for Vector {
type Output = Self;
fn mul(self, rhs: Scalar) -> Self::Output {
Self { value: self.value.iter().map(|v| v * rhs.value).collect() }
}
}
let vector = Vector { value: vec![2, 4, 6] };
let scalar = Scalar { value: 3 };
assert_eq!(vector * scalar, Vector { value: vec![6, 12, 18] });
Run