Skip to content

Commit f66ebe6

Browse files
committed
E0793: Clarify that it applies to unions as well
1 parent 0f35336 commit f66ebe6

File tree

1 file changed

+28
-1
lines changed
  • compiler/rustc_error_codes/src/error_codes

1 file changed

+28
-1
lines changed

compiler/rustc_error_codes/src/error_codes/E0793.md

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
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.
22

33
Erroneous code example:
44

@@ -45,9 +45,36 @@ unsafe {
4545
// For formatting, we can create a copy to avoid the direct reference.
4646
let copy = foo.field1;
4747
println!("{}", copy);
48+
4849
// Creating a copy can be written in a single line with curly braces.
4950
// (This is equivalent to the two lines above.)
5051
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+
Although creating a reference to a `union` field is `unsafe`, this error
61+
will still be triggered if the referenced field is not sufficiently
62+
aligned. `addr_of!` and raw pointers should be used in the same way as for struct fields.
63+
64+
```compile_fail,E0793
65+
#[repr(packed)]
66+
pub union Foo {
67+
field1: u64,
68+
field2: u8,
69+
}
70+
71+
unsafe {
72+
let foo = Foo { field1: 0 };
73+
// Accessing the field directly is fine.
74+
let val = foo.field1;
75+
76+
// A reference to a packed union field causes an error.
77+
let val = &foo.field1; // ERROR
5178
}
5279
```
5380

0 commit comments

Comments
 (0)