Rust Reference ยท Concepts
Choosing a conversion in Rust
Reference for converting values in Rust: when to use as casts, From and Into, TryFrom, FromStr and parse, ToString, AsRef, Borrow and ToOwned, with a decision table.
Rust has no implicit numeric conversions, so every change of type is spelled out. The standard library offers a small family of tools, each for a different situation. The key questions are: can the conversion fail, does it lose information, does it take ownership, and does it start from text?
as is a built-in cast between primitive types and never fails (but may truncate). From/Into are for conversions that cannot fail. TryFrom/TryInto are for conversions that can. FromStr/parse turn text into a value. ToString (through Display) turns a value into text. AsRef, Borrow and ToOwned convert between borrowed and owned views.
let a = 300_i32 as u8; // 44, silently truncated let b = u64::from(7_u32); // lossless let c = u8::try_from(300_i32); // Err(TryFromIntError)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Decision table
| You have | You want | Use |
|---|---|---|
u8 |
u32, i32, f64 (lossless) |
u32::from(x) or x.into() |
i64 |
i32 (may not fit) |
i32::try_from(x) |
f64 |
integer | x as i32 (saturates, NaN is 0) or x.round() as i32 |
| any integer | any integer, wrapping is intended | as |
&str |
number, bool, char, IP address | s.parse::<T>() |
&str |
String |
s.to_string(), String::from(s), s.to_owned(), s.into() |
value with Display |
String |
x.to_string() |
String |
&str |
&s or s.as_str() |
Vec<T> |
&[T] |
&v or v.as_slice() |
[T; N] |
Vec<T> |
Vec::from(arr) or arr.to_vec() |
&[T] |
[T; N] |
<[T; N]>::try_from(slice) |
char |
u32 / u8 |
u32::from(c) / u8::try_from(c) |
u32 |
char |
char::from_u32(n) (an Option) |
| bytes | String |
String::from_utf8(v) (fallible) or from_utf8_lossy |
&T |
&U generically |
AsRef<U> bound |
| borrowed | owned | ToOwned (to_owned()), Clone |
Option<T>/Result |
the inner value | unwrap-family, ?, match, never a cast |
Usage notes
- Prefer
From/TryFromoverasfor integers when you can;ashides lossy behavior. Clippy has lints (cast_possible_truncation) to flag them. - Implement
From, notInto. AFrom<A> for Bautomatically providesInto<B> for A. ImplementIntoyourself only whenFromis impossible because of the orphan rule. - Take
impl Into<String>,impl AsRef<str>or&strin APIs to be flexible; useAsRef<Path>for file paths. parseneeds a target type: write"5".parse::<u8>()or annotate the receiving variable. Whitespace is not trimmed (" 5".parse::<i32>()fails), and"+5"is accepted for signed and unsigned integers.- Float to int
assaturates at the integer's bounds and turns NaN into 0 since Rust 1.45. TryFrom<i64> for usizemay behave differently on 32-bit targets; always usetry_fromfor sizes.?converts errors throughFrom, so implementingFrom<ParseIntError> for MyErrorlets you use?onparseresults.- Reflexive and chained impls:
From<T> for Talways exists; there is no automaticA -> B -> Cchain.