Skip to content

Commit 6e0dc54

Browse files
committed
Auto merge of #43413 - mandeep:ops-generics, r=alexcrichton
Add generic example of std::ops::Sub in doc comments This PR adds an example of using generics with std::ops::Sub and is a follow up of PR #41612 and is related to issue #29365. I also wanted to add examples to Mul and Div, but I think these two traits are already loaded with examples.
2 parents afe145d + ae7b1f9 commit 6e0dc54

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/libcore/ops/arith.rs

+36
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,42 @@ add_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
157157
/// }
158158
/// ```
159159
///
160+
/// Here is an example of the same `Point` struct implementing the `Sub` trait
161+
/// using generics.
162+
///
163+
/// ```
164+
/// use std::ops::Sub;
165+
///
166+
/// #[derive(Debug)]
167+
/// struct Point<T> {
168+
/// x: T,
169+
/// y: T,
170+
/// }
171+
///
172+
/// // Notice that the implementation uses the `Output` associated type
173+
/// impl<T: Sub<Output=T>> Sub for Point<T> {
174+
/// type Output = Point<T>;
175+
///
176+
/// fn sub(self, other: Point<T>) -> Point<T> {
177+
/// Point {
178+
/// x: self.x - other.x,
179+
/// y: self.y - other.y,
180+
/// }
181+
/// }
182+
/// }
183+
///
184+
/// impl<T: PartialEq> PartialEq for Point<T> {
185+
/// fn eq(&self, other: &Self) -> bool {
186+
/// self.x == other.x && self.y == other.y
187+
/// }
188+
/// }
189+
///
190+
/// fn main() {
191+
/// assert_eq!(Point { x: 2, y: 3 } - Point { x: 1, y: 0 },
192+
/// Point { x: 1, y: 3 });
193+
/// }
194+
/// ```
195+
///
160196
/// Note that `RHS = Self` by default, but this is not mandatory. For example,
161197
/// [std::time::SystemTime] implements `Sub<Duration>`, which permits
162198
/// operations of the form `SystemTime = SystemTime - Duration`.

0 commit comments

Comments
 (0)