File tree 1 file changed +36
-0
lines changed
1 file changed +36
-0
lines changed Original file line number Diff line number Diff line change @@ -157,6 +157,42 @@ add_impl! { usize u8 u16 u32 u64 u128 isize i8 i16 i32 i64 i128 f32 f64 }
157
157
/// }
158
158
/// ```
159
159
///
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
+ ///
160
196
/// Note that `RHS = Self` by default, but this is not mandatory. For example,
161
197
/// [std::time::SystemTime] implements `Sub<Duration>`, which permits
162
198
/// operations of the form `SystemTime = SystemTime - Duration`.
You can’t perform that action at this time.
0 commit comments