rust 返回和错误处理anyhow

2025-06-13

导入依赖

[dependencies]
anyhow = "1.0"

使用Result

use anyhow::Result;
// 使用anyhow::Result
fn do_something_anyhow() -> anyhow::Result<()> {
//
Ok(())
}

使用Error

use anyhow::anyhow;
let err = anyhow!("Something went wrong");

fn from_io_error(io_err: std::io::Error) -> Error {
io_err.into()
}

添加错误提示

use anyhow::{Context, Result};
fn read_file(path: &str) -> Result<String> {
std::fs::read_to_string(path).with_context(|| format!("Failed to read file at {}", path))
}