Rust:Rust Type Casting: The as Keyword and Parse Methods
Rust•Type Casting

Rust Type Casting: The as Keyword and Parse Methods

Learn explicit primitive casting in Rust and converting strings to numeric types with parse().

Syntax

let f = int_val as f64; let n: u32 = str_val.parse().unwrap();

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
asOperatorExplicit conversion between primitive numeric types.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Rust locally:

fn main() {
    // 1. Primitive casting with as
    let total_sum = 185;
    let count = 4;
    let avg = total_sum as f64 / count as f64;
    println!("Average: {:.2}", avg);

    // 2. String parsing with .parse::<T>()
    let port_str = "8080";
    match port_str.parse::<u16>() {
        Ok(port) => println!("Parsed port successfully: {}", port),
        Err(e) => println!("Parse failed: {}", e),
    }
}
Expected Output:
Average: 46.25
Parsed port successfully: 8080

How It Works: Step-by-Step

  • Lines 5-6: Casts integer to f64 to perform floating-point division.
  • Lines 10-13: Parses string to u16 and handles Result with match.

Key Concepts

  • The as keyword performs primitive casting (e.g. i32 as u32).
  • .parse() returns a Result to handle invalid input safely without crashing.

Common Mistake: Calling .unwrap() on parse without error handling on untrusted input

Calling unwrap() on invalid input panics the thread. Use match or if let.

❌ Incorrect
let x: i32 = "abc".parse().unwrap(); // Panics!
✅ Correct
if let Ok(x) = "abc".parse::<i32>() { /* Safe */ }

Related Rust Tutorials & Compiler

Run and test Rust on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Rust Online Compiler