Skip to content

Commit 34e6995

Browse files
committed
Add information about numeric casts, from the nomicon
1 parent d695212 commit 34e6995

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

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

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,32 @@ For example
6767
let one = true as u8;
6868
let at_sign = 64 as char;
6969
```
70+
71+
For numeric casts, there are quite a few cases to consider:
72+
73+
* Casting between two integers of the same size (e.g. i32 -> u32) is a no-op
74+
* Casting from a larger integer to a smaller integer (e.g. u32 -> u8) will
75+
truncate
76+
* Casting from a smaller integer to a larger integer (e.g. u8 -> u32) will
77+
* zero-extend if the source is unsigned
78+
* sign-extend if the source is signed
79+
* Casting from a float to an integer will round the float towards zero
80+
* **[NOTE: currently this will cause Undefined Behavior if the rounded
81+
value cannot be represented by the target integer type][float-int]**.
82+
This includes Inf and NaN. This is a bug and will be fixed.
83+
* Casting from an integer to float will produce the floating point
84+
representation of the integer, rounded if necessary (rounding strategy
85+
unspecified)
86+
* Casting from an f32 to an f64 is perfect and lossless
87+
* Casting from an f64 to an f32 will produce the closest possible value
88+
(rounding strategy unspecified)
89+
* **[NOTE: currently this will cause Undefined Behavior if the value
90+
is finite but larger or smaller than the largest or smallest finite
91+
value representable by f32][float-float]**. This is a bug and will
92+
be fixed.
93+
94+
[float-int]: https://github.com/rust-lang/rust/issues/10184
95+
[float-float]: https://github.com/rust-lang/rust/issues/15536
7096

7197
## Pointer casts
7298

0 commit comments

Comments
 (0)