]> git.lizzy.rs Git - rust.git/blob - src/test/ui/nll/issue-57100.rs
Auto merge of #67060 - Centril:rollup-hwhdx4h, r=Centril
[rust.git] / src / test / ui / nll / issue-57100.rs
1 #![allow(unused)]
2
3 // ignore-tidy-linelength
4
5 // This tests the error messages for borrows of union fields when the unions are embedded in other
6 // structs or unions.
7
8 #[derive(Clone, Copy, Default)]
9 struct Leaf {
10     l1_u8: u8,
11     l2_u8: u8,
12 }
13
14 #[derive(Clone, Copy)]
15 union First {
16     f1_leaf: Leaf,
17     f2_leaf: Leaf,
18     f3_union: Second,
19 }
20
21 #[derive(Clone, Copy)]
22 union Second {
23     s1_leaf: Leaf,
24     s2_leaf: Leaf,
25 }
26
27 struct Root {
28     r1_u8: u8,
29     r2_union: First,
30 }
31
32 // Borrow a different field of the nested union.
33 fn nested_union() {
34     unsafe {
35         let mut r = Root {
36             r1_u8: 3,
37             r2_union: First { f3_union: Second { s2_leaf: Leaf { l1_u8: 8, l2_u8: 4 } } }
38         };
39
40         let mref = &mut r.r2_union.f3_union.s1_leaf.l1_u8;
41         //                                  ^^^^^^^
42         *mref = 22;
43         let nref = &r.r2_union.f3_union.s2_leaf.l1_u8;
44         //                              ^^^^^^^
45         //~^^ 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]
46         println!("{} {}", mref, nref)
47     }
48 }
49
50 // Borrow a different field of the first union.
51 fn first_union() {
52     unsafe {
53         let mut r = Root {
54             r1_u8: 3,
55             r2_union: First { f3_union: Second { s2_leaf: Leaf { l1_u8: 8, l2_u8: 4 } } }
56         };
57
58         let mref = &mut r.r2_union.f2_leaf.l1_u8;
59         //                         ^^^^^^^
60         *mref = 22;
61         let nref = &r.r2_union.f1_leaf.l1_u8;
62         //                     ^^^^^^^
63         //~^^ 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]
64         println!("{} {}", mref, nref)
65     }
66 }
67
68 fn main() {}