]> git.proxmox.com Git - rustc.git/blob - tests/ui/lint/fn_must_use.rs
New upstream version 1.68.2+dfsg1
[rustc.git] / tests / ui / lint / fn_must_use.rs
1 // check-pass
2
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 }
15
16 #[must_use]
17 fn need_to_use_this_associated_function_value() -> isize {
18 -1
19 }
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() {
55 need_to_use_this_value(); //~ WARN unused return value
56
57 let mut m = MyStruct { n: 2 };
58 let n = MyStruct { n: 3 };
59
60 m.need_to_use_this_method_value(); //~ WARN unused return value
61 m.is_even(); // trait method!
62 //~^ WARN unused return value
63
64 MyStruct::need_to_use_this_associated_function_value();
65 //~^ WARN unused return value
66
67 m.replace(3); // won't warn (annotation needs to be in trait definition)
68
69 // comparison methods are `must_use`
70 2.eq(&3); //~ WARN unused return value
71 m.eq(&n); //~ WARN unused return value
72
73 // lint includes comparison operators
74 2 == 3; //~ WARN unused comparison
75 m == n; //~ WARN unused comparison
76 }