Skip to content

Commit c75ccd7

Browse files
Rollup merge of rust-lang#41612 - mandeep:add-ops-generics, r=GuillaumeGomez,frewsxcv
Added generic example of std::ops::Add in doc comments We discussed on IRC how the std::ops examples were potentially missing examples using generics. This PR adds an example to std::ops::Add that shows the use of a generic type T. I'm not sure this is ready for merge as I think the two examples now make the documentation a bit verbose, but I think it's a good starting point. I'd love to hear others thoughts on this. This is in relation to the last item in issue rust-lang#29365.
2 parents 93dd1ca + a2a9d19 commit c75ccd7

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/libcore/ops.rs

+36
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,42 @@ pub trait Drop {
235235
/// }
236236
/// ```
237237
///
238+
/// Here is an example of the same `Point` struct implementing the `Add` trait
239+
/// using generics.
240+
///
241+
/// ```
242+
/// use std::ops::Add;
243+
///
244+
/// #[derive(Debug)]
245+
/// struct Point<T> {
246+
/// x: T,
247+
/// y: T,
248+
/// }
249+
///
250+
/// // Notice that the implementation uses the `Output` associated type
251+
/// impl<T: Add<Output=T>> Add for Point<T> {
252+
/// type Output = Point<T>;
253+
///
254+
/// fn add(self, other: Point<T>) -> Point<T> {
255+
/// Point {
256+
/// x: self.x + other.x,
257+
/// y: self.y + other.y,
258+
/// }
259+
/// }
260+
/// }
261+
///
262+
/// impl<T: PartialEq> PartialEq for Point<T> {
263+
/// fn eq(&self, other: &Self) -> bool {
264+
/// self.x == other.x && self.y == other.y
265+
/// }
266+
/// }
267+
///
268+
/// fn main() {
269+
/// assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 },
270+
/// Point { x: 3, y: 3 });
271+
/// }
272+
/// ```
273+
///
238274
/// Note that `RHS = Self` by default, but this is not mandatory. For example,
239275
/// [std::time::SystemTime] implements `Add<Duration>`, which permits
240276
/// operations of the form `SystemTime = SystemTime + Duration`.

0 commit comments

Comments
 (0)