]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/tests/ui/needless_borrow.rs
Rollup merge of #98429 - b-naber:use-correct-substs-discriminant-cast, r=lcnr
[rust.git] / src / tools / clippy / tests / ui / needless_borrow.rs
1 // run-rustfix
2
3 #![feature(lint_reasons)]
4
5 #[warn(clippy::all, clippy::needless_borrow)]
6 #[allow(unused_variables, clippy::unnecessary_mut_passed)]
7 fn main() {
8     let a = 5;
9     let ref_a = &a;
10     let _ = x(&a); // no warning
11     let _ = x(&&a); // warn
12
13     let mut b = 5;
14     mut_ref(&mut b); // no warning
15     mut_ref(&mut &mut b); // warn
16
17     let s = &String::from("hi");
18     let s_ident = f(&s); // should not error, because `&String` implements Copy, but `String` does not
19     let g_val = g(&Vec::new()); // should not error, because `&Vec<T>` derefs to `&[T]`
20     let vec = Vec::new();
21     let vec_val = g(&vec); // should not error, because `&Vec<T>` derefs to `&[T]`
22     h(&"foo"); // should not error, because the `&&str` is required, due to `&Trait`
23     let garbl = match 42 {
24         44 => &a,
25         45 => {
26             println!("foo");
27             &&a
28         },
29         46 => &&a,
30         47 => {
31             println!("foo");
32             loop {
33                 println!("{}", a);
34                 if a == 25 {
35                     break &ref_a;
36                 }
37             }
38         },
39         _ => panic!(),
40     };
41
42     let _ = x(&&&a);
43     let _ = x(&mut &&a);
44     let _ = x(&&&mut b);
45     let _ = x(&&ref_a);
46     {
47         let b = &mut b;
48         x(&b);
49     }
50
51     // Issue #8191
52     let mut x = 5;
53     let mut x = &mut x;
54
55     mut_ref(&mut x);
56     mut_ref(&mut &mut x);
57     let y: &mut i32 = &mut x;
58     let y: &mut i32 = &mut &mut x;
59
60     let y = match 0 {
61         // Don't lint. Removing the borrow would move 'x'
62         0 => &mut x,
63         _ => &mut *x,
64     };
65
66     *x = 5;
67
68     let s = String::new();
69     // let _ = (&s).len();
70     // let _ = (&s).capacity();
71     // let _ = (&&s).capacity();
72
73     let x = (1, 2);
74     let _ = (&x).0;
75     let x = &x as *const (i32, i32);
76     let _ = unsafe { (&*x).0 };
77 }
78
79 #[allow(clippy::needless_borrowed_reference)]
80 fn x(y: &i32) -> i32 {
81     *y
82 }
83
84 fn mut_ref(y: &mut i32) {
85     *y = 5;
86 }
87
88 fn f<T: Copy>(y: &T) -> T {
89     *y
90 }
91
92 fn g(y: &[u8]) -> u8 {
93     y[0]
94 }
95
96 trait Trait {}
97
98 impl<'a> Trait for &'a str {}
99
100 fn h(_: &dyn Trait) {}
101
102 #[allow(dead_code)]
103 fn check_expect_suppression() {
104     let a = 5;
105     #[expect(clippy::needless_borrow)]
106     let _ = x(&&a);
107 }