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