Skip to content

Commit 2f36835

Browse files
committed
Clarify casting of pointers-to-unsized
1 parent b52460f commit 2f36835

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

src/expressions/operator-expr.md

+21
Original file line numberDiff line numberDiff line change
@@ -396,6 +396,27 @@ Casts an enum to its discriminant, then uses a numeric cast if needed.
396396

397397
Casts to the `char` with the corresponding code point.
398398

399+
#### Pointer to pointer cast
400+
401+
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.
402+
Casting between pointers to unsized type preserves the pointer metadata unchanged (e.g. the slice element length remains the same).
403+
404+
To illustrate:
405+
406+
```rust
407+
#![feature(ptr_metadata)]
408+
use std::ptr;
409+
410+
let u8_slice_ptr = ptr::slice_from_raw_parts::<u8>(ptr::null(), 4);
411+
assert_eq!((ptr::null(), 4), u8_slice_ptr.to_raw_parts());
412+
413+
let u8_ptr = u8_slice_ptr as *const u8;
414+
assert_eq!((ptr::null(), ()), u8_ptr.to_raw_parts());
415+
416+
let u16_slice_ptr = u8_slice_ptr as *const [u16];
417+
assert_eq!((ptr::null(), 4), u16_slice_ptr.to_raw_parts());
418+
```
419+
399420
#### Pointer to address cast
400421

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

0 commit comments

Comments
 (0)