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.
2
2
3
3
Erroneous code example:
4
4
@@ -45,9 +45,36 @@ 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
+ 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
51
78
}
52
79
```
53
80
You can’t perform that action at this time.
0 commit comments