Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 132 ยท Variables and Types

Type Conversion and Casting

Learn how to convert between types in Rust - as casts, truncation and saturation, From and Into, TryFrom and TryInto, parse, usize indexing and char, u8 and u32 conversions.

Rust never converts one numeric type into another behind your back. i32 + i64 is a compile error, a function that wants a u64 will not take a u32 variable, and you cannot index a vector with an i32. That strictness is a feature: every conversion that might lose information, or change the sign of a number, is visible in the source code where a reader (and a reviewer) can see it.

The price is that you need to know the tools for converting. Rust has four, and picking the right one is the whole skill: the as operator (cheap, always works, can silently lose data), the From and Into traits (only for conversions that can never fail), the TryFrom and TryInto traits (for conversions that can fail, and say so with a Result), and parse (from text). By the end of the lesson you will know which to use when. The types themselves are introduced in Integers, Floats, bool and char, and the failures that can come with arithmetic in Integer Overflow and Arithmetic.

Casting with as

The as keyword converts between primitive types. It is the shortest way, it never fails, and it never panics: that also means it never tells you when something went wrong. You need to know exactly what it does in each case.

Integer to integer

When the target type is wider and the value fits, nothing special happens: 5_u8 as i32 is 5, and a negative i8 stays negative when widened to i32 (it is sign-extended). When the target is narrower, as keeps only the low bits, which is called truncation. When the sign changes, the bits are reinterpreted:

Rust as between integer types

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.

The results: 200, -5, 44, 16960, -1, 4294967295, 18446744073709551615 and -1294967296. The value 300 does not fit into a u8, so only the low 8 bits (300 mod 256 = 44) remain. -1_i32 as u32 is the all-ones bit pattern, which is the biggest u32. These are well defined but rarely what you intend, which is why code that uses as for narrowing deserves a second look. Clippy has lints for it (cast_possible_truncation, cast_sign_loss, cast_possible_wrap) that you can enable; see Clippy and rustfmt.

Float to integer

Casting a float to an integer truncates the fraction toward zero and saturates at the limits of the target type. NaN becomes 0. Since Rust 1.45 this behavior is fully defined; it cannot cause undefined behavior as it once could:

Rust as from float to integer saturates

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.

You get 3 -3, 0 255, 2147483647 -2147483648, 0, 65535 -9223372036854775808 and 2 3. Negative values clamp to 0 for unsigned types, too large values clamp to MAX, NaN gives 0, and the fractional part is simply dropped. If you want conventional rounding call round() first.

Integer to float, and back

Converting an integer to a float rounds to the nearest representable float. An f32 has only 24 bits of precision, an f64 has 53, so big integers can lose their low digits:

Rust as from integer to float loses precision

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.

The first line prints 16777216: the + 1 vanished. u64::MAX as f64 prints 18446744073709552000. The last line shows a typical use: converting an integer to a float so that division is not integer division.

bool, char and u8

as also handles some conversions with bool and char:

Rust as with bool, char and u8

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.

The output is 1 0, 65 129408, 233, a c and z. A char can be cast to any integer type (it truncates if the type is too small), but the only integer you can cast to char is a u8. That limitation is deliberate: not every u32 is a valid char, and as is not allowed to produce an invalid one:

Rust Only u8 casts to char (fails on purpose)

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.

The compiler says error[E0604]: only `u8` can be cast as `char`, not `u32` . Use char::from_u32(code) or char::try_from(code), which return an Option or a Result and force you to deal with invalid code points. You will see them later in this lesson.

as can silently truncate, wrap and saturate. Use it deliberately for bit-level work, for widening that is certain to be fine, and for float conversions where you have already checked the range. When the value comes from outside the program, prefer TryFrom.

From and Into: conversions that cannot fail

The trait From<T> describes a conversion that always succeeds, usually widening without loss. The standard library implements it for exactly those cases and for no others. Its mirror image is Into, which you get for free: if U: From<T>, then T: Into<U>.

Rust From and Into for lossless conversions

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.

The results are 15, then 7 3 65 B 1, then owned ['a', 'b', 'c'] owned. There is no From<i64> for i32, because it could lose information. The compiler will not let you write i32::from(10_i64), which is how Rust tells you that you need a fallible conversion. The table of what exists is regular: an unsigned type converts into any larger signed or unsigned type, a signed type into any larger signed type, and any integer up to 32 bits (and f32) into f64. From also converts char to u32 and u8 to char, but not u32 to char.

In a function signature, impl Into<String> accepts both &str and String, which is a handy trick for constructors:

Rust
fn greet(name: impl Into<String>) -> String {
    let name: String = name.into();
    format!("Hello, {name}!")
}

As a rule, prefer T::from(x) in code (it names the destination) and x.into() when the destination is obvious from the context, such as a function argument or a struct field. You will write your own implementations in Display and From.

TryFrom and TryInto: conversions that can fail

When a value may not fit, TryFrom<T> returns a Result. TryInto is its mirror. Both are in the prelude since the 2021 edition, so no use line is needed:

Rust TryFrom and TryInto

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.

The successful conversions print Ok(200) and Ok(65535); the failures print Err(TryFromIntError(PosOverflow)) for too large a value and Err(TryFromIntError(NegOverflow)) for too small a one (u32::try_from(-1)). The error's Display text is number too large to fit in target type or number too small to fit in target type. The error says only which side of the range you missed; it does not hold the value. Converting 0x1F980 gives Ok('๐Ÿฆ€'), while the surrogate 0xD800 is an error.

Here is the idiom you will use constantly, a checked conversion in a function that returns a Result with ? (the topic of The ? Operator):

Rust Using try_from with a question mark

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.

The three lines are Ok(25), Err("30000% is more than 255") and Err("whole is zero").

Indexing and usize

Since indices and lengths are usize, you meet conversions in nearly every program that mixes counters with collections. There are three situations.

  1. Your counter is already usize: do nothing.
  2. Your value comes from somewhere else (a file, a user, a protocol field) as u32 or i32, and you know it is in range: convert with usize::try_from(n)? or, if you accept a panic on failure, .try_into().unwrap().
  3. You are tempted to write n as usize: this works, but a negative i32 becomes a gigantic usize, which then fails the bounds check.
Rust A negative index through as (fails on purpose)

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.

The panic message is index out of bounds: the len is 3 but the index is 18446744073709551615: -1 as usize is usize::MAX. The safe form is items.get(usize::try_from(position).ok()?), or you check the sign first. With get the out-of-range index gives None instead of a panic.

Going the other way, from usize to a smaller type for a file format or a network field, also deserves try_from: a Vec can theoretically be longer than u32::MAX.

Parsing text into numbers

Text to number is the job of str::parse, which works with any type implementing FromStr. It always returns a Result, since the text may be nonsense. You met it in Reading Input; here it is next to its siblings:

Rust parse for integers, floats, bool and char

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.

Highlights: parse accepts a leading + or - but not spaces (trim first), unsigned types reject -7, floats understand exponents and the words NaN and inf, and the error messages are cannot parse integer from empty string, invalid digit found in string and number too large to fit in target type. from_str_radix parses digits in any base up to 36.

The reverse, number to text, uses to_string() (from Display), format!, or println! directly, as in Printing.

Choosing the right tool

You have You want Use
u8 / i32 ... a wider integer From / Into
any integer a narrower or different-sign integer TryFrom / TryInto (or as if you want bit truncation)
integer f64 f64::from(x) for 32 bits or less, as f64 for 64-bit values
f64 integer as after round(), floor() or a range check
u32 char char::from_u32 / char::try_from
u8 char char::from(b)
text number parse::<T>()
number text to_string() or format!

A final design note: in your own code you can often avoid conversions altogether by choosing the right type at the start. Use usize for indices and counts, and convert once, at the boundary of the program where the data comes in.

Common mistakes

  • Using as for narrowing without checking the range, so data is silently truncated.
  • Casting a possibly negative i32 with as usize and getting a huge index.
  • Expecting as to round: 2.9 as i32 is 2.
  • Looking for i32::from(i64): it does not exist on purpose. Use try_from.
  • Converting u32 to char with as: only u8 is allowed; use char::from_u32.
  • Forgetting that parse needs a type and that it does not trim spaces.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is 300_i32 as u8?

    Narrowing with as keeps only the low 8 bits: 300 mod 256 = 44. No error or panic happens, which is why as needs care.
  2. 2. Which conversion has NO From implementation in the standard library?

    From is only implemented when the conversion can never lose information. i64 to i32 can, so you need TryFrom (or as).
  3. 3. What does 3.99_f64 as i32 evaluate to, and what does f64::NAN as i32 evaluate to?

    Float to integer casts truncate toward zero, saturate at the limits, and turn NaN into 0.
  4. 4. What does u8::try_from(300_i32) return?

    TryFrom returns a Result. 300 does not fit in a u8, so you get an error value; its Display text is 'number too large to fit in target type'.
  5. 5. Which cast to char is allowed with as?

    Only u8 can be cast to char with as, because every u8 is a valid Unicode scalar value. Other integers need char::from_u32 or char::try_from.

Summary

  • Rust has no implicit numeric conversions; you pick one of four tools.
  • as always succeeds: narrowing truncates the bits, sign changes reinterpret them, float to integer truncates and saturates (NaN becomes 0), and only u8 can be cast to char.
  • From/Into exist only for lossless conversions (i64::from(i32), f64::from(u32), u32::from(char)).
  • TryFrom/TryInto return a Result for conversions that can fail (u8::try_from(300), char::try_from(u32)).
  • usize is the index type; a negative number cast with as usize becomes a huge value, so prefer usize::try_from.
  • str::parse::<T>() turns text into numbers and returns a Result; trim whitespace first.
  • Convert once at the program boundary and keep one type internally.

Next: Tuples and the Unit Type shows how to group several values of different types.