File tree Expand file tree Collapse file tree 1 file changed +28
-1
lines changed
compiler/rustc_error_codes/src/error_codes Expand file tree Collapse file tree 1 file changed +28
-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.
22
33Erroneous 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
You can’t perform that action at this time.
0 commit comments