Skip to content

Commit d695212

Browse files
committed
Attempted documentation of coercions
Trying to summarize here only the cases that will make sense at the level of the rust book
1 parent f34e6ff commit d695212

File tree

1 file changed

+19
-3
lines changed

1 file changed

+19
-3
lines changed

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

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,22 @@ different types between each other. The first, `as`, is for safe casts.
55
In contrast, `transmute` allows for arbitrary casting, and is one of the
66
most dangerous features of Rust!
77

8+
# Coercion
9+
10+
Coercion between types is implicit and has no explicit syntax. Coercion occurs
11+
in `let`, `const`, and `static` statements; in function call arguments; in
12+
field values in struct initialization; and in a function result.
13+
14+
The main cases of coercion are:
15+
16+
* `&mut T` to `&T`
17+
18+
* `*mut T` to `*const T`
19+
20+
* `&T` to `*const T`
21+
22+
* `&mut T` to `*mut T`
23+
824
# `as`
925

1026
The `as` keyword does safe casting:
@@ -31,10 +47,10 @@ For example:
3147

3248
```rust
3349
let a = "hello";
34-
let b = a as String
50+
let b = a as String;
3551
```
3652

37-
Coercions always occur implicitly so this form is only for clarity.
53+
All coercions will be made implicitly when necessary and unambiguous.
3854

3955
## Numeric casts
4056

@@ -58,7 +74,7 @@ Perhaps surprisingly, it is safe to cast pointers to and from integers, and
5874
to cast between pointers to different types subject to some constraints. It
5975
is only unsafe to dereference the pointer.
6076

61-
* `e` has type `*T`, `U` is a pointer to `*U_0`, and either `U_0: Sized` or
77+
* `e` has type `*T`, `U` has type `*U_0`, and either `U_0: Sized` or
6278
unsize_kind(`T`) = unsize_kind(`U_0`); a *ptr-ptr-cast*
6379
* `e` has type `*T` and `U` is a numeric type, while `T: Sized`; *ptr-addr-cast*
6480
* `e` is an integer and `U` is `*U_0`, while `U_0: Sized`; *addr-ptr-cast*

0 commit comments

Comments
 (0)