Rust Reference ยท Attributes
The #[must_use] attribute
Reference for Rust #[must_use]: marking types and functions whose results must not be ignored, custom messages, Result and Iterator, and how to opt out.
#[must_use] makes the compiler emit the unused_must_use warning when a value of the marked type, or the result of the marked function, is thrown away. It catches a whole family of mistakes: ignoring a Result that might hold an error, forgetting that an iterator adapter does nothing until consumed, or discarding the return value of a pure function.
It can be placed on structs, enums, unions, traits, and on functions and methods. Several standard types already carry it, including Result, Option in many methods, iterator adapters and Future.
#[must_use = "the new total is returned, not stored"] fn add(a: i32, b: i32) -> i32 { a + b }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
#[must_use] #[must_use = "message shown with the warning"]
| Placement | Effect |
|---|---|
| Function or method | Warns if the call's return value is unused |
| Type (struct, enum, union) | Warns if any expression of that type is unused |
| Trait | Warns when an impl Trait return value is unused |
Edge cases:
- Assigning to
_(let _ = value;) counts as using the value on purpose and silences the warning. - Only the value of an expression statement is checked; passing the value anywhere (a variable, an argument, a method call on it) counts as use.
Result<(), E>is stillmust_use, so even unit-valued fallible calls need handling or an explicit discard.
Usage notes
- Use it for pure functions where calling and ignoring the result is certainly a bug (
add,trim,to_uppercase), and for builders whose chained calls return the new value. - Use it for guards and handles. Types whose creation has side effects only while alive, such as lock guards, should be
#[must_use]solock();without binding is flagged. - Add a message that tells the reader what to do instead; it appears in the diagnostic.
- Lint level. The warning comes from
unused_must_use; escalate it to an error with#![deny(unused_must_use)]. - Not a guarantee. It cannot catch a value that is stored and later dropped without being looked at.
- Methods that take
&mut selfand return something useful, likeHashSet::insert, are marked so that ignoring the bool is visible.
Related
- Lint attributes,
Result::okanderr,#[deprecated] - Lessons: Result, Iterators