]> git.lizzy.rs Git - rust.git/commitdiff
Added generic example of std::ops::Add in doc comments
authormandeep <mandeep@users.noreply.github.com>
Fri, 28 Apr 2017 18:16:49 +0000 (13:16 -0500)
committermandeep <mandeep@users.noreply.github.com>
Thu, 11 May 2017 16:24:20 +0000 (11:24 -0500)
Added blank lines around example

Added comment to Add example referencing the Output type

Removed whitespace from lines 272 and 273

Removed Debug derivation from Add examples

Added Debug derivation

src/libcore/ops.rs

index 175b3a5a69ac15c86c51109154a6cdf3ef9ffac9..03cfdf5378301451d9b778d780b80f6f621bb2ea 100644 (file)
@@ -235,6 +235,42 @@ pub trait Drop {
 /// }
 /// ```
 ///
+/// Here is an example of the same `Point` struct implementing the `Add` trait
+/// using generics.
+///
+/// ```
+/// use std::ops::Add;
+///
+/// #[derive(Debug)]
+/// struct Point<T> {
+///     x: T,
+///     y: T,
+/// }
+///
+/// // Notice that the implementation uses the `Output` associated type
+/// impl<T: Add<Output=T>> Add for Point<T> {
+///     type Output = Point<T>;
+///
+///     fn add(self, other: Point<T>) -> Point<T> {
+///         Point {
+///             x: self.x + other.x,
+///             y: self.y + other.y,
+///         }
+///     }
+/// }
+///
+/// impl<T: PartialEq> PartialEq for Point<T> {
+///     fn eq(&self, other: &Self) -> bool {
+///         self.x == other.x && self.y == other.y
+///     }
+/// }
+///
+/// fn main() {
+///     assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
+///                Point { x: 3, y: 3 });
+/// }
+/// ```
+///
 /// Note that `RHS = Self` by default, but this is not mandatory. For example,
 /// [std::time::SystemTime] implements `Add<Duration>`, which permits
 /// operations of the form `SystemTime = SystemTime + Duration`.