环境
- Time 2022-01-20
- Rust 1.58.0
- Anyhow 1.0.52
概念
参考:https://docs.rs/anyhow/latest/anyhow/
示例
toml
[package]
edition = "2021"
name = "game"
version = "0.1.0"
[dependencies]
anyhow = "*"
serde = {version = "*", features = ["derive"]}
serde_json = "*"
main.rs
use anyhow::Result;
use serde::Deserialize;
#[derive(Deserialize, Default)]
struct User {
name: String,
age: u8,
}
fn main() {
let user = read_user();
user.unwrap_or_else(|e| match e.downcast_ref::<std::io::Error>() {
Some(e) => {
println!("downcast error: {:?}", e.kind());
User::default()
}
None => unreachable!(),
});
}
fn read_user() -> Result<User> {
let config = std::fs::read_to_string("user.json")?;
let user: User = serde_json::from_str(&config)?;
println!("name: {}, age: {}", user.name, user.age);
Ok(user)
}
总结
附录
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。