Skip to content

Commit 7e95f10

Browse files
committed
Clarify casting of pointers-to-unsized
1 parent f3d3953 commit 7e95f10

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/expressions/operator-expr.md

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -440,6 +440,27 @@ Casts an enum to its discriminant, then uses a numeric cast if needed.
440440

441441
Casts to the `char` with the corresponding code point.
442442

443+
#### Pointer to pointer cast
444+
445+
Casting from a pointer to unsized type to pointer to sized type discards the pointer metadata, resulting in just a pointer to the referenced memory.
446+
Casting between pointers to unsized type preserves the pointer metadata unchanged (e.g. the slice element length remains the same).
447+
448+
To illustrate:
449+
450+
```rust
451+
#![feature(ptr_metadata)]
452+
use std::ptr;
453+
454+
let u8_slice_ptr = ptr::slice_from_raw_parts::<u8>(ptr::null(), 4);
455+
assert_eq!((ptr::null(), 4), u8_slice_ptr.to_raw_parts());
456+
457+
let u8_ptr = u8_slice_ptr as *const u8;
458+
assert_eq!((ptr::null(), ()), u8_ptr.to_raw_parts());
459+
460+
let u16_slice_ptr = u8_slice_ptr as *const [u16];
461+
assert_eq!((ptr::null(), 4), u16_slice_ptr.to_raw_parts());
462+
```
463+
443464
#### Pointer to address cast
444465

445466
Casting from a raw pointer to an integer produces the machine address of the referenced memory.

0 commit comments

Comments
 (0)