[Rust] Handle Error

发布时间 2023-05-24 13:56:16作者: Zhentiw

Typescript:

import fs from "fs";

const fileName = process.argv[2];

if (fileName) {
  fs.readFileSync(fileName)
    .toString()
    .split("\n")
    .map((num) => parseInt(num, 10))
    .forEach((line) => {
      if (isNaN(line)) {
        console.log("not a number");
      } else {
        console.log(line);
      }
    });
}

 

Rust:

fn main() {
    let filename = std::env::args().nth(1).expect("the file name is required");

    let file = std::fs::read_to_string(filename).expect("unable to read the file");

    file.lines().for_each(|line| {
        if let Ok(value) = line.parse::<usize>() {
            println!("{}", value);
        } else {
            println!("{} is not a number", line);
        }
    });
}