[Rust] Handle Error

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);
        }
    });
}

 

posted @ 2023-05-24 13:52  Zhentiw  阅读(12)  评论(0编辑  收藏  举报