W3cubDocs

/Rust

Trait std::ops::Mul

pub trait Mul<RHS = Self> {
    type Output;
    fn mul(self, rhs: RHS) -> Self::Output;
}

The Mul trait is used to specify the functionality of *.

Examples

Implementing a Multipliable rational number struct:

use std::ops::Mul;

// The uniqueness of rational numbers in lowest terms is a consequence of
// the fundamental theorem of arithmetic.
#[derive(Eq)]
#[derive(PartialEq, Debug)]
struct Rational {
    nominator: usize,
    denominator: usize,
}

impl Rational {
    fn new(nominator: usize, denominator: usize) -> Self {
        if denominator == 0 {
            panic!("Zero is an invalid denominator!");
        }

        // Reduce to lowest terms by dividing by the greatest common
        // divisor.
        let gcd = gcd(nominator, denominator);
        Rational {
            nominator: nominator / gcd,
            denominator: denominator / gcd,
        }
    }
}

impl Mul for Rational {
    // The multiplication of rational numbers is a closed operation.
    type Output = Self;

    fn mul(self, rhs: Self) -> Self {
        let nominator = self.nominator * rhs.nominator;
        let denominator = self.denominator * rhs.denominator;
        Rational::new(nominator, denominator)
    }
}

// Euclid's two-thousand-year-old algorithm for finding the greatest common
// divisor.
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));

Note that RHS = Self by default, but this is not mandatory. Here is an implementation which enables multiplication of vectors by scalars, as is done in linear algebra.

use std::ops::Mul;

struct Scalar {value: usize};

#[derive(Debug)]
struct Vector {value: Vec<usize>};

impl Mul<Vector> for Scalar {
    type Output = Vector;

    fn mul(self, rhs: Vector) -> Vector {
        Vector {value: rhs.value.iter().map(|v| self.value * v).collect()}
    }
}

impl PartialEq<Vector> for Vector {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value
    }
}

let scalar = Scalar{value: 3};
let vector = Vector{value: vec![2, 4, 6]};
assert_eq!(scalar * vector, Vector{value: vec![6, 12, 18]});

Associated Types

The resulting type after applying the * operator

Required Methods

The method for the * operator

Implementors

© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.
https://doc.rust-lang.org/std/ops/trait.Mul.html