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.
22
33Erroneous code example:
44
@@ -45,9 +45,37 @@ 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+ 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
5179}
5280```
5381
You can’t perform that action at this time.
0 commit comments