Skip to content

Commit

Permalink
Rollup merge of rust-lang#59839 - KodrAus:must-use-num, r=sfackler
Browse files Browse the repository at this point in the history
Warn on unused results for operation methods on nums

From a suggestion by @llogiq

Adds a `#[must_use]` attribute to operation methods on integers that take self by value as the first operand and another value as the second. It makes it clear that these methods return the result of the operation instead of mutating `self`, which is the source of a rather embarrassing bug I had in a codebase of mine recently...

As an example:

```rust
struct Int {
   value: i64,
}

impl Int {
    fn add(&mut self, other: i64) {
        self.value.wrapping_add(other);
    }
}
```

Will produce a warning like:

```
warning: unused return value of `core::num::<impl i64>::wrapping_add` that must be used
 --> src/main.rs:7:7
  |
7 |       self.value.wrapping_add(other);
  |       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: #[warn(unused_must_use)] on by default
  = note: this returns the result of the operation, without modifying the original
```

If this is something we're on board with, we could do something similar for `f32` and `f64` too. There are probably other methods on integers that make sense.
  • Loading branch information
kennytm committed Apr 23, 2019
2 parents 0550766 + 23154db commit 5c9a234
Show file tree
Hide file tree
Showing 2 changed files with 157 additions and 1 deletion.

0 comments on commit 5c9a234

Please sign in to comment.