Rust Type Conversion
Rust never changes a value's type behind your back. If you have an i32 and need an f64, or have text and need a number, you ask for the conversion yourself. That might feel like extra typing at first, but it means a conversion can never surprise you. This page collects the main ways to convert, so you can pick the right one.
as: quick number conversions
as converts between number types. Going from a whole number to a decimal is always safe. Going the other way cuts off the decimals, and going into a smaller type can lose information, so use it with care:
fn main() {
let whole: i32 = 7;
let half = whole as f64 / 2.0;
println!("{}", half);
let price: f64 = 99.99;
println!("{}", price as u32);
let letter = 'A';
println!("{} has the code {}", letter, letter as u32);
println!("Code 66 is {}", 66u8 as char);
}3.5 99 A has the code 65 Code 66 is B
from and into: conversions that always work
When a conversion can never lose anything, the type offers from. A u8 always fits in a u32, and a &str can always become a String. into is the same conversion seen from the other side; Rust works out the target type from the variable:
fn main() {
let small: u8 = 200;
let big = u32::from(small);
let bigger: u64 = big.into();
let name = String::from("Kavya");
let city: String = "Chennai".into();
println!("{} {} {} {}", big, bigger, name, city);
}200 200 Kavya Chennai
try_from: conversions that might not fit
When a value might not fit, try_from checks for you and gives a Result. 300 does not fit in a u8 (which stops at 255), and a negative number cannot become unsigned:
fn main() {
for n in [100, 300, -5] {
match u8::try_from(n) {
Ok(v) => println!("{} fits in a u8: {}", n, v),
Err(_) => println!("{} does not fit in a u8", n),
}
}
}100 fits in a u8: 100 300 does not fit in a u8 -5 does not fit in a u8
Compare this with 300 as u8, which quietly gives 44 by wrapping around. When the value comes from outside the program, try_from is the honest choice.
Text and numbers
To turn text into a number, use parse and say the target type. To turn a number, or almost anything printable, into text, use to_string or format!:
fn main() {
let typed = " 42 ";
let n: i32 = typed.trim().parse().unwrap();
let pi: f64 = "3.14159".parse().unwrap();
let label = n.to_string() + " items";
let rounded = format!("{:.2}", pi);
println!("{} | {} | {}", n * 2, label, rounded);
}84 | 42 items | 3.14
A quick guide
| You have | You want | Use |
|---|---|---|
| a number | another number type | as, or from / try_from |
a &str | a String | String::from, to_string or into |
| text | a number | parse |
| a number | text | to_string or format! |
Practice exercises
- Convert the character 'z' to its code and back again.
- Ask the user for a number and check with
u8::try_fromwhether it fits in au8. - Turn the list of texts
["4", "8", "15"]into numbers and print their sum.