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

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

A trivial implementation of Mul. When Foo * Foo happens, it ends up calling mul, and therefore, main prints Multiplying!.

use std::ops::Mul; struct Foo; impl Mul for Foo { type Output = Foo; fn mul(self, _rhs: Foo) -> Foo { println!("Multiplying!"); self } } fn main() { Foo * Foo; }
use std::ops::Mul;

struct Foo;

impl Mul for Foo {
    type Output = Foo;

    fn mul(self, _rhs: Foo) -> Foo {
        println!("Multiplying!");
        self
    }
}

fn main() {
    Foo * Foo;
}

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.

fn main() { 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]}); }
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