前回の続き。
anyhowクレートを使用してエラー処理をハンドリングするコードです。
[package]
name = "samplecli"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
clap = { version = "3.1.6", features = ["derive"] }
anyhow = { version = "1.0.57" }
use anyhow::{Context, Result};
fn get_int_from_file() -> Result<i32> {
let path = "number.txt";
let num_str = std::fs::read_to_string(path)
.with_context(|| format!("failed to read string from {}", path))?;
num_str
.trim()
.parse::<i32>()
.map(|t| t * 2)
.context("failed to parse string")
}
fn main() {
match get_int_from_file() {
Ok(x) => println!("{}", x),
Err(e) => println!("{}", e),
}
}
「RUST勉強中、6/4の積み上げ」への1件のフィードバック