summaryrefslogtreecommitdiffstats
path: root/src/tools/clippy/tests/ui/unnecessary_struct_initialization.fixed
blob: eae1271d1aa726ce2b6228d31ab5e4ccc11cd256 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
//@run-rustfix

#![allow(clippy::incorrect_clone_impl_on_copy_type, unused)]
#![warn(clippy::unnecessary_struct_initialization)]

struct S {
    f: String,
}

#[derive(Clone, Copy)]
struct T {
    f: u32,
}

struct U {
    f: u32,
}

impl Clone for U {
    fn clone(&self) -> Self {
        // Do not lint: `Self` does not implement `Copy`
        Self { ..*self }
    }
}

#[derive(Copy)]
struct V {
    f: u32,
}

impl Clone for V {
    fn clone(&self) -> Self {
        // Lint: `Self` implements `Copy`
        *self
    }
}

fn main() {
    // Should lint: `a` would be consumed anyway
    let a = S { f: String::from("foo") };
    let mut b = a;

    // Should lint: `b` would be consumed, and is mutable
    let c = &mut b;

    // Should not lint as `d` is not mutable
    let d = S { f: String::from("foo") };
    let e = &mut S { ..d };

    // Should lint as `f` would be consumed anyway
    let f = S { f: String::from("foo") };
    let g = &f;

    // Should lint: the result of an expression is mutable
    let h = &mut *Box::new(S { f: String::from("foo") });

    // Should not lint: `m` would be both alive and borrowed
    let m = T { f: 17 };
    let n = &T { ..m };

    // Should not lint: `m` should not be modified
    let o = &mut T { ..m };
    o.f = 32;
    assert_eq!(m.f, 17);

    // Should not lint: `m` should not be modified
    let o = &mut T { ..m } as *mut T;
    unsafe { &mut *o }.f = 32;
    assert_eq!(m.f, 17);

    // Should lint: the result of an expression is mutable and temporary
    let p = &mut *Box::new(T { f: 5 });
}