Skip to content
Tutorials Center
My learning

Topics

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.

Rust
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

Rust Numbers: as, From and TryFrom

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.

Rust Text: parse and to_string

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.

Rust Your own From, Into and TryFrom

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/TryFrom over as for integers when you can; as hides lossy behavior. Clippy has lints (cast_possible_truncation) to flag them.
  • Implement From, not Into. A From<A> for B automatically provides Into<B> for A. Implement Into yourself only when From is impossible because of the orphan rule.
  • Take impl Into<String>, impl AsRef<str> or &str in APIs to be flexible; use AsRef<Path> for file paths.
  • parse needs 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 as saturates at the integer's bounds and turns NaN into 0 since Rust 1.45.
  • TryFrom<i64> for usize may behave differently on 32-bit targets; always use try_from for sizes.
  • ? converts errors through From, so implementing From<ParseIntError> for MyError lets you use ? on parse results.
  • Reflexive and chained impls: From<T> for T always exists; there is no automatic A -> B -> C chain.