Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

replace Mul example with something more evocative of multiplication #35860

Merged
merged 1 commit into from
Aug 23, 2016
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 47 additions & 10 deletions src/libcore/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,26 +274,63 @@ sub_impl! { usize u8 u16 u32 u64 isize i8 i16 i32 i64 f32 f64 }
///
/// # Examples
///
/// A trivial implementation of `Mul`. When `Foo * Foo` happens, it ends up
/// calling `mul`, and therefore, `main` prints `Multiplying!`.
/// Implementing a `Mul`tipliable rational number struct:
///
/// ```
/// use std::ops::Mul;
///
/// struct Foo;
/// // 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 Foo {
/// type Output = Foo;
/// impl Mul for Rational {
/// // The multiplication of rational numbers is a closed operation.
/// type Output = Self;
///
/// fn mul(self, _rhs: Foo) -> Foo {
/// println!("Multiplying!");
/// self
/// fn mul(self, rhs: Self) -> Self {
/// let nominator = self.nominator * rhs.nominator;
/// let denominator = self.denominator * rhs.denominator;
/// Rational::new(nominator, denominator)
/// }
/// }
///
/// fn main() {
/// Foo * Foo;
/// // 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));
/// ```
#[lang = "mul"]
#[stable(feature = "rust1", since = "1.0.0")]
Expand Down