anyhowを使ってエラーの型に応じた処理を書く

rustのanyhowを使って、エラーの型に応じた処理を書く方法が分からなかったのでメモ。

以下の★のところで処理を記述している。

use anyhow::{Context, Result};

fn get_int() -> Result<i32> {
  let path  = "test.txt";
  let num_s = std::fs::read_to_string(path)
    .map(|s| s.trim().to_string())
    .with_context(|| format!("failed to read string from {}", path))?;
  num_s
    .parse::<i32>()
    .with_context(|| format!("failed to parse string '{}'", num_s))
}

fn main() {
  match get_int() {
    Ok(x)  => println!("{}", x),
    Err(e) => {
      println!("{}", e);
      if let Some(error) = e.downcast_ref::<std::num::ParseIntError>() {
        // ★ std::num::ParseIntErrorが発生したときの処理
        println!("Parse Error {:#?}", error);
      } else if let Some(error) = e.downcast_ref::<std::io::Error>() {
        // ★ std::io::Errorが発生したときの処理
        println!("I/O Error {:#?}", error);
      } else {
        println!("Other Error");
      }
    },
  }
}

Growiでrustをコードハイライトする

  1. Growiの「設定」→「カスタマイズ」を開く。
  2. 「カスタム HTML Header」に以下を追記して更新する。
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.0.1/highlight.min.js" defer></script>

URLは、以下のページからコピペしている。
highlight.js - Libraries - cdnjs - The #1 free and open source CDN built to make life easier for developers
3. 次の記述でコードハイライトを確認した。

 ```rust
 let x: u32 = 10;
 ```