summaryrefslogtreecommitdiffstats
path: root/tests/ui/nll/issue-57100.rs
blob: f15929334bb40a44c99253fd471a0aeed8538706 (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
#![allow(unused)]


// This tests the error messages for borrows of union fields when the unions are embedded in other
// structs or unions.

#[derive(Clone, Copy, Default)]
struct Leaf {
    l1_u8: u8,
    l2_u8: u8,
}

#[derive(Clone, Copy)]
union First {
    f1_leaf: Leaf,
    f2_leaf: Leaf,
    f3_union: Second,
}

#[derive(Clone, Copy)]
union Second {
    s1_leaf: Leaf,
    s2_leaf: Leaf,
}

struct Root {
    r1_u8: u8,
    r2_union: First,
}

// Borrow a different field of the nested union.
fn nested_union() {
    unsafe {
        let mut r = Root {
            r1_u8: 3,
            r2_union: First { f3_union: Second { s2_leaf: Leaf { l1_u8: 8, l2_u8: 4 } } }
        };

        let mref = &mut r.r2_union.f3_union.s1_leaf.l1_u8;
        //                                  ^^^^^^^
        *mref = 22;
        let nref = &r.r2_union.f3_union.s2_leaf.l1_u8;
        //                              ^^^^^^^
        //~^^ ERROR cannot borrow `r.r2_union.f3_union` (via `r.r2_union.f3_union.s2_leaf.l1_u8`) as immutable because it is also borrowed as mutable (via `r.r2_union.f3_union.s1_leaf.l1_u8`) [E0502]
        println!("{} {}", mref, nref)
    }
}

// Borrow a different field of the first union.
fn first_union() {
    unsafe {
        let mut r = Root {
            r1_u8: 3,
            r2_union: First { f3_union: Second { s2_leaf: Leaf { l1_u8: 8, l2_u8: 4 } } }
        };

        let mref = &mut r.r2_union.f2_leaf.l1_u8;
        //                         ^^^^^^^
        *mref = 22;
        let nref = &r.r2_union.f1_leaf.l1_u8;
        //                     ^^^^^^^
        //~^^ ERROR cannot borrow `r.r2_union` (via `r.r2_union.f1_leaf.l1_u8`) as immutable because it is also borrowed as mutable (via `r.r2_union.f2_leaf.l1_u8`) [E0502]
        println!("{} {}", mref, nref)
    }
}

fn main() {}