RRust By Example
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

This example demonstrates how to use numeric conversions in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.

Key Concepts

  • Rust's strong type system catches errors at compile time
  • Ownership and borrowing rules ensure memory safety
  • Pattern matching makes code expressive and exhaustive

Related Topics

Browse more examples in the basics category to build a complete understanding of this topic.

More Basics Examples