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:
| Parameter | Type | Description |
|---|---|---|
| as | Operator | Explicit conversion between primitive numeric types. |
Ready-to-Run Code Example
Executable in CompilraRun 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
Rust Default Immutability, the mut Modifier, and Shadowing
Master Rust variable binding model: default immutability, explicit mut modifier, variable shadowing, and compile-time thread safety.
Rust Operators: Arithmetic, Comparison, and Checked Math
Master Rust arithmetic, logical, and bitwise operators with compile-time safety.
Rust Exhaustive Match Pattern Matching and Expression Control Flow
Master expression-driven pattern matching in Rust using exhaustive match blocks, match guards, range patterns (..=), and wildcards (_).
Rust Online Compiler
Open in Compilra IDE
Run and test Rust on Compilra
Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.