W3cubDocs

/Rust

Trait std::ops::Div

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

Implementing a Dividable rational number struct:

use std::ops::Div;

// 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 Div for Rational {
    // The division of rational numbers is a closed operation.
    type Output = Self;

    fn div(self, rhs: Self) -> Self {
        if rhs.nominator == 0 {
            panic!("Cannot divide by zero-valued `Rational`!");
        }

        let nominator = self.nominator * rhs.denominator;
        let denominator = self.denominator * rhs.nominator;
        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
}

fn main() {
    assert_eq!(Rational::new(1, 2), Rational::new(2, 4));
    assert_eq!(Rational::new(1, 2) / Rational::new(3, 4),
               Rational::new(2, 3));
}

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.

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

© 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.Div.html