Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

TODO: Error handling in Rust

[package]
name = "error-handling"
version = "0.1.0"
edition = "2024"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
fn main() {
    let args = std::env::args().collect::<Vec<String>>();
    if args.len() != 2 {
        eprintln!("Usage: {} FILENAME", args[0]);
        std::process::exit(1);
    }
    let filename = &args[1];
    println!("{}", divide(filename));
}


fn divide(filename: &str) -> Result<i32, std::io::Error> {
    let content = std::fs::read_to_string(filename)?;
    let content = content.strip_suffix('\n').unwrap();
    let (dividend, divisor) = content.split_once(',').unwrap();
    let dividend = dividend.parse::<i32>().unwrap();
    let divisor = divisor.parse::<i32>().unwrap();
    dividend / divisor
}


// fn divide(filename: &str) -> i32 {
//     let content = std::fs::read_to_string(filename).unwrap();
//     let content = content.strip_suffix('\n').unwrap();
//     let (dividend, divisor) = content.split_once(',').unwrap();
//     let dividend = dividend.parse::<i32>().unwrap();
//     let divisor = divisor.parse::<i32>().unwrap();
//     dividend / divisor
// }
1
30,2
30,0
forty,two