diff options
| author | bors <bors@rust-lang.org> | 2017-07-24 00:24:16 +0000 |
|---|---|---|
| committer | bors <bors@rust-lang.org> | 2017-07-24 00:24:16 +0000 |
| commit | 6e0dc54872c11b07d70143caa2ddc87aeca17362 (patch) | |
| tree | d1a3511f29966c58c6a8bb9d83cd0a8e6ee31159 /src/libcore | |
| parent | afe145d227c5739ec5305f6b5352230a58ebb029 (diff) | |
| parent | ae7b1f9f2ce333d6762cb47501b575758c3cc6de (diff) | |
| download | rust-6e0dc54872c11b07d70143caa2ddc87aeca17362.tar.gz rust-6e0dc54872c11b07d70143caa2ddc87aeca17362.zip | |
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.
Diffstat (limited to 'src/libcore')
| -rw-r--r-- | src/libcore/ops/arith.rs | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/src/libcore/ops/arith.rs b/src/libcore/ops/arith.rs index c6fb75f6ace..d898f9146cd 100644 --- a/src/libcore/ops/arith.rs +++ b/src/libcore/ops/arith.rs @@ -157,6 +157,42 @@ add_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 } /// } /// ``` /// +/// Here is an example of the same `Point` struct implementing the `Sub` trait +/// using generics. +/// +/// ``` +/// use std::ops::Sub; +/// +/// #[derive(Debug)] +/// struct Point<T> { +/// x: T, +/// y: T, +/// } +/// +/// // Notice that the implementation uses the `Output` associated type +/// impl<T: Sub<Output=T>> Sub for Point<T> { +/// type Output = Point<T>; +/// +/// fn sub(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: 2, y: 3 } - Point { x: 1, y: 0 }, +/// Point { x: 1, y: 3 }); +/// } +/// ``` +/// /// Note that `RHS = Self` by default, but this is not mandatory. For example, /// [std::time::SystemTime] implements `Sub<Duration>`, which permits /// operations of the form `SystemTime = SystemTime - Duration`. |
