In Rust, every value has a type: i32, f64, String, and so on. Sometimes you need to convert a value from one type to another.
Common type conversion functions:
x.to_string() // converts i32 or f64 → String
s.parse::<i32>().unwrap() // converts &str → i32
s.parse::<f64>().unwrap() // converts &str → f64
x as i32 // casts f64 → i32 (drops decimal)
Here are some examples:
let score: i32 = 42;
let score_str = score.to_string(); // "42"
let weight: f64 = 70.8;
let weight_int = weight as i32; // 70 (decimal dropped)
let count = "100";
let count_int: i32 = count.parse().unwrap(); // 100
Note that casting an f64 to i32 with as i32 simply drops the decimal - it does not round.
Assignment
Follow the Coding Tutorial and convert each variable to a different type!
Hint
Use .to_string(), as i32 casting, and .parse().unwrap().
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check