Skip to content

Commit f21dcbe

Browse files
author
Jonathan Turner
authored
Rollup merge of rust-lang#35806 - matthew-piziak:addassign-example, r=steveklabnik
replace `AddAssign` example with something more evocative of addition This is analogous to PR rust-lang#35709 for the `Add` trait.
2 parents 1136f42 + 6c66eaa commit f21dcbe

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

src/libcore/ops.rs

+21-10
Original file line numberDiff line numberDiff line change
@@ -980,25 +980,36 @@ shr_impl_all! { u8 u16 u32 u64 usize i8 i16 i32 i64 isize }
980980
///
981981
/// # Examples
982982
///
983-
/// A trivial implementation of `AddAssign`. When `Foo += Foo` happens, it ends up
984-
/// calling `add_assign`, and therefore, `main` prints `Adding!`.
983+
/// This example creates a `Point` struct that implements the `AddAssign`
984+
/// trait, and then demonstrates add-assigning to a mutable `Point`.
985985
///
986986
/// ```
987987
/// use std::ops::AddAssign;
988988
///
989-
/// struct Foo;
989+
/// #[derive(Debug)]
990+
/// struct Point {
991+
/// x: i32,
992+
/// y: i32,
993+
/// }
990994
///
991-
/// impl AddAssign for Foo {
992-
/// fn add_assign(&mut self, _rhs: Foo) {
993-
/// println!("Adding!");
995+
/// impl AddAssign for Point {
996+
/// fn add_assign(&mut self, other: Point) {
997+
/// *self = Point {
998+
/// x: self.x + other.x,
999+
/// y: self.y + other.y,
1000+
/// };
9941001
/// }
9951002
/// }
9961003
///
997-
/// # #[allow(unused_assignments)]
998-
/// fn main() {
999-
/// let mut foo = Foo;
1000-
/// foo += Foo;
1004+
/// impl PartialEq for Point {
1005+
/// fn eq(&self, other: &Self) -> bool {
1006+
/// self.x == other.x && self.y == other.y
1007+
/// }
10011008
/// }
1009+
///
1010+
/// let mut point = Point { x: 1, y: 0 };
1011+
/// point += Point { x: 2, y: 3 };
1012+
/// assert_eq!(point, Point { x: 3, y: 3 });
10021013
/// ```
10031014
#[lang = "add_assign"]
10041015
#[stable(feature = "op_assign_traits", since = "1.8.0")]

0 commit comments

Comments
 (0)