Skip to content

Additional text and examples about casting #30114

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 1, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 19 additions & 7 deletions src/doc/book/casting-between-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,24 @@ Coercion occurs in `let`, `const`, and `static` statements; in
function call arguments; in field values in struct initialization; and in a
function result.

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

* `&mut T` to `&T`

An analogous conversion is to remove mutability from a
[raw pointer](raw-pointers.md):

* `*mut T` to `*const T`

References can also be coerced to raw pointers:

* `&T` to `*const T`

* `&mut T` to `*mut T`

* A custom coercion using [`Deref`](deref-coercions.md)


Custom coercions may be defined using [`Deref`](deref-coercions.md).

Coercion is transitive.

# `as`

Expand Down Expand Up @@ -71,6 +77,7 @@ For example
```rust
let one = true as u8;
let at_sign = 64 as char;
let two_hundred = -56i8 as u8;
```

The semantics of numeric casts are:
Expand Down Expand Up @@ -101,9 +108,14 @@ The semantics of numeric casts are:

## Pointer casts

Perhaps surprisingly, it is safe to cast pointers to and from integers, and
to cast between pointers to different types subject to some constraints. It
is only unsafe to dereference the pointer.
Perhaps surprisingly, it is safe to cast [raw pointers](raw-pointers.md) to and
from integers, and to cast between pointers to different types subject to
some constraints. It is only unsafe to dereference the pointer:

```rust
let a = 300 as *const char; // a pointer to location 300
let b = a as u32;
```

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

Expand Down