]> git.lizzy.rs Git - rust.git/blob - src/docs/return_self_not_must_use.txt
[Arithmetic] Consider literals
[rust.git] / src / docs / return_self_not_must_use.txt
1 ### What it does
2 This lint warns when a method returning `Self` doesn't have the `#[must_use]` attribute.
3
4 ### Why is this bad?
5 Methods returning `Self` often create new values, having the `#[must_use]` attribute
6 prevents users from "forgetting" to use the newly created value.
7
8 The `#[must_use]` attribute can be added to the type itself to ensure that instances
9 are never forgotten. Functions returning a type marked with `#[must_use]` will not be
10 linted, as the usage is already enforced by the type attribute.
11
12 ### Limitations
13 This lint is only applied on methods taking a `self` argument. It would be mostly noise
14 if it was added on constructors for example.
15
16 ### Example
17 ```
18 pub struct Bar;
19 impl Bar {
20     // Missing attribute
21     pub fn bar(&self) -> Self {
22         Self
23     }
24 }
25 ```
26
27 Use instead:
28 ```
29 // It's better to have the `#[must_use]` attribute on the method like this:
30 pub struct Bar;
31 impl Bar {
32     #[must_use]
33     pub fn bar(&self) -> Self {
34         Self
35     }
36 }
37
38 // Or on the type definition like this:
39 #[must_use]
40 pub struct Bar;
41 impl Bar {
42     pub fn bar(&self) -> Self {
43         Self
44     }
45 }
46 ```