エラーのハンドリングの勉強。
まずはハンドリングしない場合のコード。
fn get_int_from_file() -> i32 {
let path = "number.txt";
let num_str = std::fs::read_to_string(path).expect("failed to open the file.");
let ret = num_str
.trim()
.parse::<i32>()
.expect("failed to parse string to a number.");
ret * 2
}
fn main() {
println!("{}", get_int_from_file());
}
taki@DESKTOP-4VF3GEO:~/rust/samplecli$ echo 42 > number.txt
taki@DESKTOP-4VF3GEO:~/rust/samplecli$ cargo run --bin err_panic
Compiling samplecli v0.1.0 (/home/taki/rust/samplecli)
Finished dev [unoptimized + debuginfo] target(s) in 0.38s
Running `target/debug/err_panic`
84
taki@DESKTOP-4VF3GEO:~/rust/samplecli$ echo hoge > number.txt
taki@DESKTOP-4VF3GEO:~/rust/samplecli$ cargo run --bin err_panic
Finished dev [unoptimized + debuginfo] target(s) in 0.01s
Running `target/debug/err_panic`
thread 'main' panicked at 'failed to parse string to a number.: ParseIntError { kind: InvalidDigit }', src/bin/err_panic.rs:8:10
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
taki@DESKTOP-4VF3GEO:~/rust/samplecli$
「RUST勉強中、5/14の積み上げ」への1件のフィードバック