You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/expressions/operator-expr.md
+45
Original file line number
Diff line number
Diff line change
@@ -70,6 +70,50 @@ let a = && && mut 10;
70
70
leta=&&&&mut10;
71
71
```
72
72
73
+
### Raw address-of operators
74
+
75
+
Related to the borrow operators are the raw address-of operators, which do not have first-class syntax, but are exposed via the macros `ptr::addr_of!(expr)` and `ptr::addr_of_mut!(expr)`.
76
+
Like with `&`/`&mut`, the expression is evaluated in place expression context.
77
+
The difference is that `&`/`&mut` create *references* of type `&T`/`&mut T`, while `ptr::addr_of!(expr)` creates a (const) raw pointer of type `*const T` and `ptr::addr_of_mut!(expr)` creates a mutable raw pointer of type `*mut T`.
78
+
79
+
The raw address-of operators must be used whenever the place expression denotes a place that is not properly aligned or does not store a valid value as determined by its type.
80
+
In those situations, using a borrow operator would cause [undefined behavior] by creating an invalid reference, but a raw pointer may still be constructed using an address-of operator.
81
+
82
+
**Example of creating a raw pointer to an unaligned place (through a `packed` struct):**
83
+
84
+
```rust
85
+
usestd::ptr;
86
+
87
+
#[repr(packed)]
88
+
structPacked {
89
+
f1:u8,
90
+
f2:u16,
91
+
}
92
+
93
+
letpacked=Packed { f1:1, f2:2 };
94
+
// `&packed.f2` would create an unaligned reference, and thus be Undefined Behavior!
0 commit comments