How to parse string to number

Use the `parse()` method on your string slice, which returns a `Result` that you must handle to avoid panics.

Use the parse() method on your string slice, which returns a Result that you must handle to avoid panics. For quick scripts, you can use the ? operator or unwrap(), but in production code, always match on the Result to handle invalid input gracefully.

Here is the standard approach using parse() with explicit error handling:

fn main() {
    let input = "42";
    
    // Attempt to parse into a u32
    match input.parse::<u32>() {
        Ok(num) => println!("Parsed number: {}", num),
        Err(e) => println!("Failed to parse: {}", e),
    }

    // Parsing a float
    let float_str = "3.14";
    if let Ok(f) = float_str.parse::<f64>() {
        println!("Parsed float: {}", f);
    }
}

If you are inside a function that already returns a Result, you can use the ? operator for cleaner propagation of errors:

fn process_value(s: &str) -> Result<i32, std::num::ParseIntError> {
    // The ? operator automatically returns the error if parsing fails
    let value: i32 = s.parse()?;
    Ok(value * 2)
}

For parsing integers with specific bases (like hexadecimal or binary), use the parse::<i32>() method combined with the from_str_radix function if you need to specify the radix explicitly, though parse handles standard decimal strings by default. If you need to parse a string that might contain whitespace, trim it first:

let dirty = "  100  ";
let clean = dirty.trim();
let num: u32 = clean.parse().unwrap(); // Safe here because we know it's clean

Remember that parse() is generic, so you must specify the target type (e.g., i32, u64, f32, f64) using turbofish syntax (::<Type>) or type inference. If the string contains non-numeric characters or is out of range for the target type, it will return an Err containing a ParseIntError or ParseFloatError. Avoid using unwrap() in library code unless you are absolutely certain the input is valid, as it will cause a runtime panic on failure.