Trait std::ops::Mul1.0.0[][src]

pub trait Mul<Rhs = Self> {
    type Output;
    #[must_use]
    fn mul(self, rhs: Rhs) -> Self::Output;
}
Expand description

乘法运算符 *

请注意,默认情况下 RhsSelf,但这不是强制性的。

Examples

可复制的有理数

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

Associated Types

应用 * 运算符后的结果类型。

Required methods

执行 * 操作。

Example

assert_eq!(12 * 2, 24);
Run

Implementors