Skip to content

Rust Type Casting

Rust won’t automatically convert one type into another for you — if you mix an i32 and an f64 in the same expression, it won’t compile. You have to convert explicitly. This is on purpose: silent conversions are a common source of bugs in other languages.

Use the as keyword to cast one number type into another:

fn main() {
let x: i32 = 10;
let y: f64 = x as f64; // i32 -> f64
println!("{y}");
}
▶ Try it Yourself

This matters more than it looks — try dividing two integers without casting, and you’ll get integer division instead of the decimal result you probably wanted:

fn main() {
let a = 10;
let b = 3;
println!("{}", a / b); // 3 (integer division)
println!("{}", a as f64 / b as f64); // 3.3333333333333335
}
▶ Try it Yourself

Casting from a bigger type to a smaller one (like i32 to u8) doesn’t fail — it just truncates, which can give you a surprising result:

fn main() {
let big: i32 = 300;
let small = big as u8; // u8 only holds 0-255
println!("{small}"); // 44, not 300 — it wrapped around
}
▶ Try it Yourself

Casting with as only works between number types. To turn text into a number — say, something typed by a user — use .parse():

fn main() {
let text = "42";
let number: i32 = text.parse().expect("not a valid number");
println!("{}", number + 8);
}

Output:

50
▶ Try it Yourself

.parse() can fail (what if the text isn’t a number at all?), so it returns a Result rather than the number directly. We haven’t covered Result yet — for now, .expect("message") is a simple way to say “crash with this message if it fails.” You’ll see the proper way to handle it on the Result page.

Going the other way is simpler — almost every type can turn into a String with .to_string():

fn main() {
let number = 42;
let text = number.to_string();
println!("{}", text + "!");
}
▶ Try it Yourself
  • Rust never converts types automatically — you always cast explicitly.
  • Use as to convert between number types: x as f64, x as u8.
  • Casting down to a smaller type truncates silently — it won’t error, so be careful.
  • Use .parse() to turn text into a number, and .to_string() to go the other way.

Quick check

1. What happens when you divide two integers like 10 / 3 in Rust without casting?

2. What happens when you cast 300_i32 as u8?

3. What does .parse() return when converting a string to a number, since the conversion can fail?

Score: 0 / 3