File tree Expand file tree Collapse file tree 1 file changed +29
-1
lines changed
compiler/rustc_error_codes/src/error_codes Expand file tree Collapse file tree 1 file changed +29
-1
lines changed Original file line number Diff line number Diff line change 1
- An unaligned reference to a field of a [ packed] struct got created.
1
+ An unaligned reference to a field of a [ packed] ` struct ` or ` union ` was created.
2
2
3
3
Erroneous code example:
4
4
@@ -45,9 +45,37 @@ unsafe {
45
45
// For formatting, we can create a copy to avoid the direct reference.
46
46
let copy = foo.field1;
47
47
println!("{}", copy);
48
+
48
49
// Creating a copy can be written in a single line with curly braces.
49
50
// (This is equivalent to the two lines above.)
50
51
println!("{}", { foo.field1 });
52
+
53
+ // A reference to a field that will always be sufficiently aligned is safe:
54
+ println!("{}", foo.field2);
55
+ }
56
+ ```
57
+
58
+ ### Unions
59
+
60
+ Even though creating a reference to a ` union ` field is ` unsafe ` , this error
61
+ will still be triggered when referencing a field that is not sufficiently
62
+ aligned. ` addr_of! ` and raw pointers should be used the same way as is done
63
+ for ` struct ` fields.
64
+
65
+ ``` compile_fail,E0793
66
+ #[repr(packed)]
67
+ pub union Foo {
68
+ field1: u64,
69
+ field2: u8,
70
+ }
71
+
72
+ unsafe {
73
+ let foo = Foo { field1: 0 };
74
+ // Accessing the field directly is fine.
75
+ let val = foo.field1;
76
+
77
+ // A reference to a packed union field causes an error.
78
+ let val = &foo.field1; // ERROR
51
79
}
52
80
```
53
81
You can’t perform that action at this time.
0 commit comments