]> git.proxmox.com Git - rustc.git/blame - src/tools/clippy/tests/ui/single_match.rs
New upstream version 1.52.1+dfsg1
[rustc.git] / src / tools / clippy / tests / ui / single_match.rs
CommitLineData
f20569fa
XL
1#![warn(clippy::single_match)]
2
3fn dummy() {}
4
5fn single_match() {
6 let x = Some(1u8);
7
8 match x {
9 Some(y) => {
10 println!("{:?}", y);
11 },
12 _ => (),
13 };
14
15 let x = Some(1u8);
16 match x {
17 // Note the missing block braces.
18 // We suggest `if let Some(y) = x { .. }` because the macro
19 // is expanded before we can do anything.
20 Some(y) => println!("{:?}", y),
21 _ => (),
22 }
23
24 let z = (1u8, 1u8);
25 match z {
26 (2..=3, 7..=9) => dummy(),
27 _ => {},
28 };
29
30 // Not linted (pattern guards used)
31 match x {
32 Some(y) if y == 0 => println!("{:?}", y),
33 _ => (),
34 }
35
36 // Not linted (no block with statements in the single arm)
37 match z {
38 (2..=3, 7..=9) => println!("{:?}", z),
39 _ => println!("nope"),
40 }
41}
42
43enum Foo {
44 Bar,
45 Baz(u8),
46}
47use std::borrow::Cow;
48use Foo::*;
49
50fn single_match_know_enum() {
51 let x = Some(1u8);
52 let y: Result<_, i8> = Ok(1i8);
53
54 match x {
55 Some(y) => dummy(),
56 None => (),
57 };
58
59 match y {
60 Ok(y) => dummy(),
61 Err(..) => (),
62 };
63
64 let c = Cow::Borrowed("");
65
66 match c {
67 Cow::Borrowed(..) => dummy(),
68 Cow::Owned(..) => (),
69 };
70
71 let z = Foo::Bar;
72 // no warning
73 match z {
74 Bar => println!("42"),
75 Baz(_) => (),
76 }
77
78 match z {
79 Baz(_) => println!("42"),
80 Bar => (),
81 }
82}
83
84// issue #173
85fn if_suggestion() {
86 let x = "test";
87 match x {
88 "test" => println!(),
89 _ => (),
90 }
91
92 #[derive(PartialEq, Eq)]
93 enum Foo {
94 A,
95 B,
96 C(u32),
97 }
98
99 let x = Foo::A;
100 match x {
101 Foo::A => println!(),
102 _ => (),
103 }
104
105 const FOO_C: Foo = Foo::C(0);
106 match x {
107 FOO_C => println!(),
108 _ => (),
109 }
110
111 match &&x {
112 Foo::A => println!(),
113 _ => (),
114 }
115
116 let x = &x;
117 match &x {
118 Foo::A => println!(),
119 _ => (),
120 }
121
122 enum Bar {
123 A,
124 B,
125 }
126 impl PartialEq for Bar {
127 fn eq(&self, rhs: &Self) -> bool {
128 matches!((self, rhs), (Self::A, Self::A) | (Self::B, Self::B))
129 }
130 }
131 impl Eq for Bar {}
132
133 let x = Bar::A;
134 match x {
135 Bar::A => println!(),
136 _ => (),
137 }
138}
139
140macro_rules! single_match {
141 ($num:literal) => {
142 match $num {
143 15 => println!("15"),
144 _ => (),
145 }
146 };
147}
148
149fn main() {
150 single_match!(5);
151}