diff options
| author | Martin Pool <mbp@sourcefrog.net> | 2015-11-30 07:59:14 -0800 |
|---|---|---|
| committer | Martin Pool <mbp@sourcefrog.net> | 2015-11-30 08:02:18 -0800 |
| commit | f183d7a26ed5c39634612486a45240d067ba0abf (patch) | |
| tree | 13da93021e1df6b0ca7b8a19923782a3dffad12a | |
| parent | fd2626cc3f5c3652b5a9b4d3b7f850ff2e8e8590 (diff) | |
| download | rust-f183d7a26ed5c39634612486a45240d067ba0abf.tar.gz rust-f183d7a26ed5c39634612486a45240d067ba0abf.zip | |
Additional text and examples around casting
| -rw-r--r-- | src/doc/book/casting-between-types.md | 26 |
1 files changed, 19 insertions, 7 deletions
diff --git a/src/doc/book/casting-between-types.md b/src/doc/book/casting-between-types.md index e2b114b7e54..e0e9b75d464 100644 --- a/src/doc/book/casting-between-types.md +++ b/src/doc/book/casting-between-types.md @@ -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 coercion may be defined using [`Deref`](deref-coercions.md). + +Coercion is transitive. # `as` @@ -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: @@ -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: |
