You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The `#[must_use]` attribute can be applied to types or functions where failing to explicitly consider them or their output is almost certainly a bug.
4
+
5
+
As an example, `Result` is `#[must_use]` because failing to consider it may indicate a caller didn't realise a method was fallible:
6
+
7
+
```rust
8
+
// If `check_status` returns a `Result`, we might assume this
9
+
// call was infallible
10
+
check_status();
11
+
```
12
+
13
+
Operators like `saturating_add` are also `#[must_use]` because failing to consider its output might indicate a caller didn't realise they don't mutate the left hand side:
14
+
15
+
```rust
16
+
leta=42;
17
+
letb=13;
18
+
19
+
// A caller might assume this method mutates `a`
20
+
a.saturating_add(b);
21
+
```
22
+
23
+
Combinators produced by the `Iterator` trait are `#[must_use]` because failing to consider them might indicate a caller didn't realize `Iterator`s are lazy and won't actually do anything unless you drive them:
24
+
25
+
```rust
26
+
// A caller might not realise none of this code won't do anything
27
+
// unless they call `collect`, `count`, etc.
28
+
slice.iter().filter(|v|v>10).map(|v|v+2);
29
+
```
30
+
31
+
On the other hand, `thread::JoinHandle` isn't `#[must_use]` because spawning and forgetting background work is a legitimate pattern and forcing callers to ignore it is less likely to catch bugs:
32
+
33
+
```rust
34
+
thread::spawn(|| {
35
+
// this background work isn't waited on
36
+
});
37
+
```
38
+
39
+
## For reviewers
40
+
41
+
The `#[must_use]` attribute only produces warnings, so it can technically be introduced at any time. To avoid accumulating nuisance warnings though ping `@rust-lang/libs` for input before adding new `#[must_use]` attributes to existing types and functions.
0 commit comments