Skip to content

Commit cf4432a

Browse files
author
Jonathan Turner
authored
Rollup merge of rust-lang#35709 - matthew-piziak:add-trait-example, r=GuillaumeGomez
replace `Add` example with something more evocative of addition Currently most of the operator traits use trivial implementation examples that only perform side effects. Honestly, that might not be too bad for the sake of documentation; but anyway, here's a proposal to move a slightly modified version of the module-level point-addition example into the `Add` documentation, since it's more evocative of addition semantics. Part of rust-lang#29365
2 parents 05fb19c + dcee93a commit cf4432a

File tree

1 file changed

+23
-11
lines changed

1 file changed

+23
-11
lines changed

src/libcore/ops.rs

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -67,8 +67,7 @@
6767
//! }
6868
//! ```
6969
//!
70-
//! See the documentation for each trait for a minimum implementation that
71-
//! prints something to the screen.
70+
//! See the documentation for each trait for an example implementation.
7271
7372
#![stable(feature = "rust1", since = "1.0.0")]
7473

@@ -171,25 +170,38 @@ macro_rules! forward_ref_binop {
171170
///
172171
/// # Examples
173172
///
174-
/// A trivial implementation of `Add`. When `Foo + Foo` happens, it ends up
175-
/// calling `add`, and therefore, `main` prints `Adding!`.
173+
/// This example creates a `Point` struct that implements the `Add` trait, and
174+
/// then demonstrates adding two `Point`s.
176175
///
177176
/// ```
178177
/// use std::ops::Add;
179178
///
180-
/// struct Foo;
179+
/// #[derive(Debug)]
180+
/// struct Point {
181+
/// x: i32,
182+
/// y: i32,
183+
/// }
181184
///
182-
/// impl Add for Foo {
183-
/// type Output = Foo;
185+
/// impl Add for Point {
186+
/// type Output = Point;
184187
///
185-
/// fn add(self, _rhs: Foo) -> Foo {
186-
/// println!("Adding!");
187-
/// self
188+
/// fn add(self, other: Point) -> Point {
189+
/// Point {
190+
/// x: self.x + other.x,
191+
/// y: self.y + other.y,
192+
/// }
193+
/// }
194+
/// }
195+
///
196+
/// impl PartialEq for Point {
197+
/// fn eq(&self, other: &Self) -> bool {
198+
/// self.x == other.x && self.y == other.y
188199
/// }
189200
/// }
190201
///
191202
/// fn main() {
192-
/// Foo + Foo;
203+
/// assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
204+
/// Point { x: 3, y: 3 });
193205
/// }
194206
/// ```
195207
#[lang = "add"]

0 commit comments

Comments
 (0)