]> git.lizzy.rs Git - rust.git/blob - src/test/ui/fn_must_use.rs
Auto merge of #54939 - pnkfelix:issue-54478-dont-prefer-dynamic-in-doc-tests, r=Quiet...
[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     #[must_use]
27     fn need_to_use_this_associated_function_value() -> isize {
28         -1
29     }
30 }
31
32 trait EvenNature {
33     #[must_use = "no side effects"]
34     fn is_even(&self) -> bool;
35 }
36
37 impl EvenNature for MyStruct {
38     fn is_even(&self) -> bool {
39         self.n % 2 == 0
40     }
41 }
42
43 trait Replaceable {
44     fn replace(&mut self, substitute: usize) -> usize;
45 }
46
47 impl Replaceable for MyStruct {
48     // ↓ N.b.: `#[must_use]` attribute on a particular trait implementation
49     // method won't work; the attribute should be on the method signature in
50     // the trait's definition.
51     #[must_use]
52     fn replace(&mut self, substitute: usize) -> usize {
53         let previously = self.n;
54         self.n = substitute;
55         previously
56     }
57 }
58
59 #[must_use = "it's important"]
60 fn need_to_use_this_value() -> bool {
61     false
62 }
63
64 fn main() {
65     need_to_use_this_value(); //~ WARN unused return value
66
67     let mut m = MyStruct { n: 2 };
68     let n = MyStruct { n: 3 };
69
70     m.need_to_use_this_method_value(); //~ WARN unused return value
71     m.is_even(); // trait method!
72     //~^ WARN unused return value
73
74     MyStruct::need_to_use_this_associated_function_value();
75     //~^ WARN unused return value
76
77     m.replace(3); // won't warn (annotation needs to be in trait definition)
78
79     // comparison methods are `must_use`
80     2.eq(&3); //~ WARN unused return value
81     m.eq(&n); //~ WARN unused return value
82
83     // lint includes comparison operators
84     2 == 3; //~ WARN unused comparison
85     m == n; //~ WARN unused comparison
86 }