[Rust] Error handling with Enum
We can use Reuslt
enum to do error handling
type Result<V, E> {
Err(E),
Ok(V)
}
Example:
// (): empty
// uszie: just return a integre as error for demo
fn error_me(throw: bool) -> Result<(), usize> {
if throw {
return Err(7)
}
return Ok(())
}
fn main() -> Result<(), usize> {
let value = error_me(false)? // ? will try to unwrap you Err, if it is an Err return Err, if it is not then unwrap the value and return the value
/**
// error_me(false)?: the same as following code
let value = match error_me(false) {
Err(e) => return Err(e),
Ok(v) => v
}
*/
if error_me(true).is_ok() {
// never come here, because throw Err
}
// error_me(true).expect("Program crash, here is why")
// expect() will panic in case of an Err, printing the provided message
Ok(())
}
Using Anyhow library to handle error:
https://github.com/dtolnay/anyhow
Install: cargo add anyhow
use anyhow::{Result, anyhow, Context};
use std::path::PathBuf;
fn error_me(throw: bool) -> Result<()> {
if throw {
return Err(anyhow!("error when throw is true"));
}
// Attempt to read a file that doesn't exist, adding context to the error
std::fs::read(PathBuf::from("/foo")).context("unable to do this")
Ok(())
}
fn main() -> Result<()> {
let value = error_me(false)? // ? will try to unwrap you Err, if it is an Err return Err, if it is not then unwrap the value and return the value
/**
// error_me(false)?: the same as following code
let value = match error_me(false) {
Err(e) => return Err(e),
Ok(v) => v
}
*/
if error_me(true).is_ok() {
// never come here, because throw Err
}
// error_me(true).expect("Program crash, here is why")
// expect() will panic in case of an Err, printing the provided message
Ok(())
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2023-02-15 [Typescript] Creating Chainable Method Abstractions with Generics and the Builder Pattern - 05
2021-02-15 [Node] Install packages correctly and avoid attacks
2020-02-15 【时间管理】猴子理论 ”monkey-on-the-back” Analogy
2020-02-15 【时间管理】GTD:Getting things done
2019-02-15 [Webpack] Create Separate webpack Configs for Development and Production with webpack-merge
2019-02-15 [Algorithm] Reverse array of Chars by word
2018-02-15 [Tools] Using mobile device for debugging your mobile web site