Skip to content

Commit 5000bd2

Browse files
committed
Rollup merge of rust-lang#30114 - sourcefrog:doc-casts2, r=Manishearth
2 parents e4ab039 + b00b32c commit 5000bd2

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 coercions may be defined using [`Deref`](deref-coercions.md).
33+
34+
Coercion is transitive.
2935

3036
# `as`
3137

@@ -64,6 +70,7 @@ For example
6470
```rust
6571
let one = true as u8;
6672
let at_sign = 64 as char;
73+
let two_hundred = -56i8 as u8;
6774
```
6875

6976
The semantics of numeric casts are:
@@ -94,9 +101,14 @@ The semantics of numeric casts are:
94101

95102
## Pointer casts
96103

97-
Perhaps surprisingly, it is safe to cast pointers to and from integers, and
98-
to cast between pointers to different types subject to some constraints. It
99-
is only unsafe to dereference the pointer.
104+
Perhaps surprisingly, it is safe to cast [raw pointers](raw-pointers.md) to and
105+
from integers, and to cast between pointers to different types subject to
106+
some constraints. It is only unsafe to dereference the pointer:
107+
108+
```rust
109+
let a = 300 as *const char; // a pointer to location 300
110+
let b = a as u32;
111+
```
100112

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

0 commit comments

Comments
 (0)