]>
Commit | Line | Data |
---|---|---|
f9f354fc | 1 | // check-pass |
ff7c6d11 | 2 | |
ea8adc8c XL |
3 | #![warn(unused_must_use)] |
4 | ||
5 | #[derive(PartialEq, Eq)] | |
6 | struct MyStruct { | |
7 | n: usize, | |
8 | } | |
9 | ||
10 | impl MyStruct { | |
11 | #[must_use] | |
12 | fn need_to_use_this_method_value(&self) -> usize { | |
13 | self.n | |
14 | } | |
0bf4aa26 XL |
15 | |
16 | #[must_use] | |
17 | fn need_to_use_this_associated_function_value() -> isize { | |
18 | -1 | |
19 | } | |
ea8adc8c XL |
20 | } |
21 | ||
22 | trait EvenNature { | |
23 | #[must_use = "no side effects"] | |
24 | fn is_even(&self) -> bool; | |
25 | } | |
26 | ||
27 | impl EvenNature for MyStruct { | |
28 | fn is_even(&self) -> bool { | |
29 | self.n % 2 == 0 | |
30 | } | |
31 | } | |
32 | ||
33 | trait Replaceable { | |
34 | fn replace(&mut self, substitute: usize) -> usize; | |
35 | } | |
36 | ||
37 | impl Replaceable for MyStruct { | |
38 | // ↓ N.b.: `#[must_use]` attribute on a particular trait implementation | |
39 | // method won't work; the attribute should be on the method signature in | |
40 | // the trait's definition. | |
41 | #[must_use] | |
42 | fn replace(&mut self, substitute: usize) -> usize { | |
43 | let previously = self.n; | |
44 | self.n = substitute; | |
45 | previously | |
46 | } | |
47 | } | |
48 | ||
49 | #[must_use = "it's important"] | |
50 | fn need_to_use_this_value() -> bool { | |
51 | false | |
52 | } | |
53 | ||
54 | fn main() { | |
ff7c6d11 | 55 | need_to_use_this_value(); //~ WARN unused return value |
ea8adc8c XL |
56 | |
57 | let mut m = MyStruct { n: 2 }; | |
58 | let n = MyStruct { n: 3 }; | |
59 | ||
ff7c6d11 | 60 | m.need_to_use_this_method_value(); //~ WARN unused return value |
ea8adc8c | 61 | m.is_even(); // trait method! |
ff7c6d11 | 62 | //~^ WARN unused return value |
ea8adc8c | 63 | |
0bf4aa26 XL |
64 | MyStruct::need_to_use_this_associated_function_value(); |
65 | //~^ WARN unused return value | |
66 | ||
ea8adc8c XL |
67 | m.replace(3); // won't warn (annotation needs to be in trait definition) |
68 | ||
69 | // comparison methods are `must_use` | |
ff7c6d11 XL |
70 | 2.eq(&3); //~ WARN unused return value |
71 | m.eq(&n); //~ WARN unused return value | |
ea8adc8c XL |
72 | |
73 | // lint includes comparison operators | |
ff7c6d11 XL |
74 | 2 == 3; //~ WARN unused comparison |
75 | m == n; //~ WARN unused comparison | |
ea8adc8c | 76 | } |