0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

rust result型について

Posted at

この問題をRustで解いていたときに

use std::io;

fn main() {
    let subjects: [&str; 3] = ["国語", "社会", "理科"];
    let mut scores: [i32; 3] = [0; 3];

    let mut input = String::new();
    for (i, subjects) in subjects.iter().enumerate() {
        print!("\n{}の点数=", subjects);
        io::stdin().read_line(&mut input);
        scores[i] = input.trim().parse::<i32>().expect("TypeError");
    }

    let sum: i32 = scores.iter().sum();
    let averave = sum as f64 / 3 as f64;

    println!("合計点は{}点です。\n平均点は{}点です。", sum, averave);
}

このようにぷろぐらむを組んでコンパイルしようとしたところ

warning: unused `Result` that must be used
  --> r011.rs:10:9
   |
10 |         io::stdin().read_line(&mut input);
   |         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: this `Result` may be an `Err` variant, which should be handled
   = note: `#[warn(unused_must_use)]` on by default
help: use `let _ = ...` to ignore the resulting value
   |
10 |         let _ = io::stdin().read_line(&mut input);
   |         +++++++

warning: 1 warning emitted

こんな感じでWarningが出てきた。

調べたところ、
この警告は、io::stdin().read_line(&mut input); の戻り値 Result<usize, std::io::Error> を無視しているために発生しているとのこと

  • read_lineResult<usize, std::io::Error> を返す関数であり、入力の読み取りが成功すれば Ok(読み取ったバイト数) を返し、失敗すれば Err(エラー情報) を返します。
  • Rust では、Result 型を無視すると「エラーハンドリングを忘れている可能性がある」とみなされ、#[warn(unused_must_use)] により警告が発生します。

これを無視しないためには、.expect().unwrap()をもちいてエラーハンドリングを行うらしい

解決用のコードは以下に

io::stdin().read_line(&mut input).expect("読み取りに失敗しました");
io::stdin().read_line(&mut input).unwrap();
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?