beginnerBasics
Numeric Conversions
Convert between numeric types safely.
Numeric Conversions
Convert between numeric types safely.
Difficulty
Beginner
Code
rust
fn main() {
let x: i32 = 42;
let y: f64 = x as f64;
println!("i32 -> f64: {}", y);
let z: i64 = x as i64;
println!("i32 -> i64: {}", z);
// safe conversion with try_from
let big: i32 = 300;
let small: u8 = u8::try_from(big).unwrap_or(255);
println!("300 as u8 (clamped): {}", small);
// parsing strings
let n: i32 = "42".parse().unwrap();
println!("parsed: {}", n);
}Explanation
as casts numbers. try_from for safe conversion.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the basics category to build a complete understanding of this topic.