Skip to content

Commit f183d7a

Browse files
committed
Additional text and examples around casting
1 parent fd2626c commit f183d7a

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

src/doc/book/casting-between-types.md

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -14,18 +14,24 @@ Coercion occurs in `let`, `const`, and `static` statements; in
1414
function call arguments; in field values in struct initialization; and in a
1515
function result.
1616

17-
The main cases of coercion are:
17+
The most common case of coercion is removing mutability from a reference:
1818

1919
* `&mut T` to `&T`
20+
21+
An analogous conversion is to remove mutability from a
22+
[raw pointer](raw-pointers.md):
2023

2124
* `*mut T` to `*const T`
25+
26+
References can also be coerced to raw pointers:
2227

2328
* `&T` to `*const T`
2429

2530
* `&mut T` to `*mut T`
26-
27-
* A custom coercion using [`Deref`](deref-coercions.md)
28-
31+
32+
Custom coercion may be defined using [`Deref`](deref-coercions.md).
33+
34+
Coercion is transitive.
2935

3036
# `as`
3137

@@ -71,6 +77,7 @@ For example
7177
```rust
7278
let one = true as u8;
7379
let at_sign = 64 as char;
80+
let two_hundred = -56i8 as u8;
7481
```
7582

7683
The semantics of numeric casts are:
@@ -101,9 +108,14 @@ The semantics of numeric casts are:
101108

102109
## Pointer casts
103110

104-
Perhaps surprisingly, it is safe to cast pointers to and from integers, and
105-
to cast between pointers to different types subject to some constraints. It
106-
is only unsafe to dereference the pointer.
111+
Perhaps surprisingly, it is safe to cast [raw pointers](raw-pointers.md) to and
112+
from integers, and to cast between pointers to different types subject to
113+
some constraints. It is only unsafe to dereference the pointer:
114+
115+
```rust
116+
let a = 300 as *const char; // a pointer to location 300
117+
let b = a as u32;
118+
```
107119

108120
`e as U` is a valid pointer cast in any of the following cases:
109121

0 commit comments

Comments
 (0)