]> git.lizzy.rs Git - rust.git/blob - tests/ui/let_unit.rs
Allow more complex expressions in `let_unit_value`
[rust.git] / tests / ui / let_unit.rs
1 // run-rustfix
2
3 #![warn(clippy::let_unit_value)]
4 #![allow(clippy::no_effect)]
5 #![allow(unused_variables)]
6
7 macro_rules! let_and_return {
8     ($n:expr) => {{
9         let ret = $n;
10     }};
11 }
12
13 fn main() {
14     let _x = println!("x");
15     let _y = 1; // this is fine
16     let _z = ((), 1); // this as well
17     if true {
18         let _a = ();
19     }
20
21     consume_units_with_for_loop(); // should be fine as well
22
23     multiline_sugg();
24
25     let_and_return!(()) // should be fine
26 }
27
28 // Related to issue #1964
29 fn consume_units_with_for_loop() {
30     // `for_let_unit` lint should not be triggered by consuming them using for loop.
31     let v = vec![(), (), ()];
32     let mut count = 0;
33     for _ in v {
34         count += 1;
35     }
36     assert_eq!(count, 3);
37
38     // Same for consuming from some other Iterator<Item = ()>.
39     let (tx, rx) = ::std::sync::mpsc::channel();
40     tx.send(()).unwrap();
41     drop(tx);
42
43     count = 0;
44     for _ in rx.iter() {
45         count += 1;
46     }
47     assert_eq!(count, 1);
48 }
49
50 fn multiline_sugg() {
51     let v: Vec<u8> = vec![2];
52
53     let _ = v
54         .into_iter()
55         .map(|i| i * 2)
56         .filter(|i| i % 2 == 0)
57         .map(|_| ())
58         .next()
59         .unwrap();
60 }
61
62 #[derive(Copy, Clone)]
63 pub struct ContainsUnit(()); // should be fine
64
65 fn _returns_generic() {
66     fn f<T>() -> T {
67         unimplemented!()
68     }
69     fn f2<T, U>(_: T) -> U {
70         unimplemented!()
71     }
72     fn f3<T>(x: T) -> T {
73         x
74     }
75     fn f4<T>(mut x: Vec<T>) -> T {
76         x.pop().unwrap()
77     }
78
79     let _: () = f(); // Ok
80     let x: () = f(); // Lint.
81
82     let _: () = f2(0i32); // Ok
83     let x: () = f2(0i32); // Lint.
84
85     let _: () = f3(()); // Lint
86     let x: () = f3(()); // Lint
87
88     let _: () = f4(vec![()]); // Lint
89     let x: () = f4(vec![()]); // Lint
90
91     // Ok
92     let _: () = {
93         let x = 5;
94         f2(x)
95     };
96
97     let _: () = if true { f() } else { f2(0) }; // Ok
98     let x: () = if true { f() } else { f2(0) }; // Lint
99
100     // Ok
101     let _: () = match Some(0) {
102         None => f2(1),
103         Some(0) => f(),
104         Some(1) => f2(3),
105         Some(_) => f2('x'),
106     };
107
108     // Lint
109     let _: () = match Some(0) {
110         None => f2(1),
111         Some(0) => f(),
112         Some(1) => f2(3),
113         Some(_) => (),
114     };
115 }