Rust has a great attribute you can add to structs called must_use
. It is used on the Result<T, E>
enum in the standard library, which looks like this:
#[derive(Clone, Copy, PartialEq, PartialOrd, Eq, Ord, Debug, Hash)]
#[must_use = "this `Result` may be an `Err` variant, which should be handled"]
#[stable(feature = "rust1", since = "1.0.0")]
pub enum Result<T, E> {
/// Contains the success value
#[stable(feature = "rust1", since = "1.0.0")]
Ok(#[stable(feature = "rust1", since = "1.0.0")] T),
/// Contains the error value
#[stable(feature = "rust1", since = "1.0.0")]
Err(#[stable(feature = "rust1", since = "1.0.0")] E),
}
And on std::iter::Map
, it looks like this:
#[must_use = "iterator adaptors are lazy and do nothing unless consumed"]
pub struct Map<I, F> { /* fields omitted */ }
So what does this attribute do? From the docs:
must_use
– on structs and enums, will warn if a value of this type isn’t used or assigned to a variable. You may also include an optional message by using#[must_use = "message"]
which will be given alongside the warning.