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

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

The Div trait is used to specify the functionality of /.

Examples

A trivial implementation of Div. When Foo / Foo happens, it ends up calling div, and therefore, main prints Dividing!.

use std::ops::Div; struct Foo; impl Div for Foo { type Output = Foo; fn div(self, _rhs: Foo) -> Foo { println!("Dividing!"); self } } fn main() { Foo / Foo; }
use std::ops::Div;

struct Foo;

impl Div for Foo {
    type Output = Foo;

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

fn main() {
    Foo / Foo;
}

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

fn main() { use std::ops::Div; struct Scalar {value: f32}; #[derive(Debug)] struct Vector {value: Vec<f32>}; impl Div<Scalar> for Vector { type Output = Vector; fn div(self, rhs: Scalar) -> Vector { Vector {value: self.value.iter().map(|v| v / rhs.value).collect()} } } impl PartialEq<Vector> for Vector { fn eq(&self, other: &Self) -> bool { self.value == other.value } } let scalar = Scalar{value: 2f32}; let vector = Vector{value: vec![2f32, 4f32, 6f32]}; assert_eq!(vector / scalar, Vector{value: vec![1f32, 2f32, 3f32]}); }
use std::ops::Div;

struct Scalar {value: f32};

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

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

    fn div(self, rhs: Scalar) -> Vector {
        Vector {value: self.value.iter().map(|v| v / rhs.value).collect()}
    }
}

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

let scalar = Scalar{value: 2f32};
let vector = Vector{value: vec![2f32, 4f32, 6f32]};
assert_eq!(vector / scalar, Vector{value: vec![1f32, 2f32, 3f32]});

Associated Types

The resulting type after applying the / operator

Required Methods

The method for the / operator

Implementors