1 unstable release
0.2.1 | Apr 10, 2024 |
---|---|
0.2.0 |
|
0.1.4 |
|
#21 in #result
262 downloads per month
6KB
93 lines
opt2r
lib.rs
:
A simple crate(library) that provides a way to convert Option to Result.
Usage
use opt2r::OptionToResult;
const CUSTOM_ERROR_CODE_OPTION_IS_NONE: i32 = 1;
const CUSTOM_ERROR_STR_OPTION_IS_NONE: &str = "Custom Error: Option is None.";
fn example1() -> opt2r::Result<()> {
let a = make_some().ok_or_()?;
let a = make_some().ok_or(opt2r::opt_is_none!())?;
let b = make_none().ok_or_()?;
Ok(())
}
fn example2() -> Result<(), i32> {
let a = make_some().ok_or(opt2r::opt_is_none_i32!())?;
//let b = make_none().ok_or_()?;
let b = make_none().ok_or(opt2r::err!(CUSTOM_ERROR_CODE_OPTION_IS_NONE))?;
Ok(())
}
fn example3() -> Result<(), String> {
let a = make_some().ok_or_()?;
let a = make_some().ok_or(opt2r::opt_is_none!())?;
let a = make_some().ok_or(opt2r::err!(CUSTOM_ERROR_STR_OPTION_IS_NONE))?;
let a = make_some().ok_or(opt2r::Error::new(CUSTOM_ERROR_STR_OPTION_IS_NONE))?;
let b = make_none().ok_or_()?;
Ok(())
}
fn example4() -> Result<(), Box<dyn opt2r::StdError>> {
let a = make_some().ok_or_()?;
let a = make_some().ok_or(opt2r::opt_is_none!())?;
let b = make_none().ok_or_()?;
Ok(())
}
fn main() {
if let Err(err) = example1() {
println!("example1 err={}, {}", err, err.error_value());
}
if let Err(err) = example2() {
println!("example2 err={}", err);
}
if let Err(err) = example3() {
println!("example3 err={}", err);
}
//example4().unwrap();
if let Err(err) = example4() {
println!("example4 err={}", err);
}
}
fn make_some() -> Option<i32> {
Some(100)
}
fn make_none() -> Option<f64> {
None
}