]> git.lizzy.rs Git - rust.git/blob - tests/ui/option_if_let_else.rs
Merge remote-tracking branch 'upstream/master' into rustup
[rust.git] / tests / ui / option_if_let_else.rs
1 // run-rustfix
2 #![warn(clippy::option_if_let_else)]
3 #![allow(clippy::redundant_closure)]
4 #![allow(clippy::ref_option_ref)]
5
6 fn bad1(string: Option<&str>) -> (bool, &str) {
7     if let Some(x) = string {
8         (true, x)
9     } else {
10         (false, "hello")
11     }
12 }
13
14 fn else_if_option(string: Option<&str>) -> Option<(bool, &str)> {
15     if string.is_none() {
16         None
17     } else if let Some(x) = string {
18         Some((true, x))
19     } else {
20         Some((false, ""))
21     }
22 }
23
24 fn unop_bad(string: &Option<&str>, mut num: Option<i32>) {
25     let _ = if let Some(s) = *string { s.len() } else { 0 };
26     let _ = if let Some(s) = &num { s } else { &0 };
27     let _ = if let Some(s) = &mut num {
28         *s += 1;
29         s
30     } else {
31         &mut 0
32     };
33     let _ = if let Some(ref s) = num { s } else { &0 };
34     let _ = if let Some(mut s) = num {
35         s += 1;
36         s
37     } else {
38         0
39     };
40     let _ = if let Some(ref mut s) = num {
41         *s += 1;
42         s
43     } else {
44         &mut 0
45     };
46 }
47
48 fn longer_body(arg: Option<u32>) -> u32 {
49     if let Some(x) = arg {
50         let y = x * x;
51         y * y
52     } else {
53         13
54     }
55 }
56
57 fn impure_else(arg: Option<i32>) {
58     let side_effect = || {
59         println!("return 1");
60         1
61     };
62     let _ = if let Some(x) = arg {
63         x
64     } else {
65         // map_or_else must be suggested
66         side_effect()
67     };
68 }
69
70 fn test_map_or_else(arg: Option<u32>) {
71     let _ = if let Some(x) = arg {
72         x * x * x * x
73     } else {
74         let mut y = 1;
75         y = (y + 2 / y) / 2;
76         y = (y + 2 / y) / 2;
77         y
78     };
79 }
80
81 fn negative_tests(arg: Option<u32>) -> u32 {
82     let _ = if let Some(13) = arg { "unlucky" } else { "lucky" };
83     for _ in 0..10 {
84         let _ = if let Some(x) = arg {
85             x
86         } else {
87             continue;
88         };
89     }
90     let _ = if let Some(x) = arg {
91         return x;
92     } else {
93         5
94     };
95     7
96 }
97
98 fn main() {
99     let optional = Some(5);
100     let _ = if let Some(x) = optional { x + 2 } else { 5 };
101     let _ = bad1(None);
102     let _ = else_if_option(None);
103     unop_bad(&None, None);
104     let _ = longer_body(None);
105     test_map_or_else(None);
106     let _ = negative_tests(None);
107     let _ = impure_else(None);
108 }