]> git.lizzy.rs Git - rust.git/blob - src/test/ui/fn_must_use.rs
Auto merge of #50665 - alexcrichton:fix-single-item-path-warnings, r=oli-obk
[rust.git] / src / test / ui / fn_must_use.rs
1 // Copyright 2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // compile-pass
12
13 #![warn(unused_must_use)]
14
15 #[derive(PartialEq, Eq)]
16 struct MyStruct {
17     n: usize,
18 }
19
20 impl MyStruct {
21     #[must_use]
22     fn need_to_use_this_method_value(&self) -> usize {
23         self.n
24     }
25 }
26
27 trait EvenNature {
28     #[must_use = "no side effects"]
29     fn is_even(&self) -> bool;
30 }
31
32 impl EvenNature for MyStruct {
33     fn is_even(&self) -> bool {
34         self.n % 2 == 0
35     }
36 }
37
38 trait Replaceable {
39     fn replace(&mut self, substitute: usize) -> usize;
40 }
41
42 impl Replaceable for MyStruct {
43     // ↓ N.b.: `#[must_use]` attribute on a particular trait implementation
44     // method won't work; the attribute should be on the method signature in
45     // the trait's definition.
46     #[must_use]
47     fn replace(&mut self, substitute: usize) -> usize {
48         let previously = self.n;
49         self.n = substitute;
50         previously
51     }
52 }
53
54 #[must_use = "it's important"]
55 fn need_to_use_this_value() -> bool {
56     false
57 }
58
59 fn main() {
60     need_to_use_this_value(); //~ WARN unused return value
61
62     let mut m = MyStruct { n: 2 };
63     let n = MyStruct { n: 3 };
64
65     m.need_to_use_this_method_value(); //~ WARN unused return value
66     m.is_even(); // trait method!
67     //~^ WARN unused return value
68
69     m.replace(3); // won't warn (annotation needs to be in trait definition)
70
71     // comparison methods are `must_use`
72     2.eq(&3); //~ WARN unused return value
73     m.eq(&n); //~ WARN unused return value
74
75     // lint includes comparison operators
76     2 == 3; //~ WARN unused comparison
77     m == n; //~ WARN unused comparison
78 }