#try #ok #wrap #catch #throw

no-std tryvial

Small crate for ok-wrapping and try blocks

2 unstable releases

0.2.0 Oct 18, 2022
0.1.2 Oct 11, 2022
0.1.1 Oct 11, 2022
0.1.0 Oct 10, 2022

#1238 in Rust patterns

Download history 131/week @ 2023-12-13 143/week @ 2023-12-20 12/week @ 2023-12-27 68/week @ 2024-01-03 314/week @ 2024-01-10 254/week @ 2024-01-17 485/week @ 2024-01-24 203/week @ 2024-01-31 251/week @ 2024-02-07 331/week @ 2024-02-14 388/week @ 2024-02-21 363/week @ 2024-02-28 526/week @ 2024-03-06 559/week @ 2024-03-13 411/week @ 2024-03-20 148/week @ 2024-03-27

1,793 downloads per month

MIT/Apache

8KB
62 lines

tryvial

A small crate for Ok-wrapping and try blocks. This is compatible with Result, Option, and any type implementing the unstable std::ops::Try trait.

This crate does not require nightly Rust.

Overview

The macro try_fn is used to perform Ok-wrapping on the return value of a function.

Before:

fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("Enter your name: ");
    let mut name = String::new();
    std::io::stdin().read_line(&mut name)?;
    println!("Hello, {name}!");
    Ok(()) // this is ugly
}

After:

#[try_fn]
fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("Enter your name: ");
    let mut name = String::new();
    std::io::stdin().read_line(&mut name)?;
    println!("Hello, {name}!");
}

The macro try_block is an implementation of "try blocks" from nightly rust.

let result: Result<T, E> = try_block! {
   let a = do_one(x)?;
   let b = do_two(a)?;
   b
};

The macro wrap_ok simply wraps an expression with the "ok" variant for a given Try type.

assert_eq!(Some(42), wrap_ok!(42));

License

MIT or Apache-2.0

Dependencies

~42KB