#macro #break #continue #return #unwrap

unwrap_or

Four easy unwrap Result and Option macros that allow for any inline-scoped code for things like return, continue, and break

2 stable releases

Uses old Rust 2015

1.0.1 Jul 28, 2023
1.0.0 Dec 14, 2021

#845 in Rust patterns

Download history 127/week @ 2024-07-20 90/week @ 2024-07-27 115/week @ 2024-08-03 244/week @ 2024-08-10 507/week @ 2024-08-17 173/week @ 2024-08-24 281/week @ 2024-08-31 245/week @ 2024-09-07 127/week @ 2024-09-14 192/week @ 2024-09-21 69/week @ 2024-09-28 167/week @ 2024-10-05 305/week @ 2024-10-12 72/week @ 2024-10-19 85/week @ 2024-10-26 90/week @ 2024-11-02

580 downloads per month
Used in 2 crates

Custom license

4KB

unwrap_or

Unwrap-or provides four macros that allow you to use code in the same scope as the calling function. They are similar to Rust's unwrap_or_else, but the provided code is not in a closure, but in the function itself.

This allows for more flexibility in what you can write. You can have a return, break, or continue statement when an error occurs, without worrying about any complicated return logic to make it happen. You can also directly reference variables in the calling function without having to move them into the closure.

Here's an example of using it:

fn a_function_which_may_fail() -> Result<String, String> {
	Error("There was an error!")
}

fn another_function() -> Result<(), String> {
	let _ok_value = unwrap_ok_or!(a_function_which_may_fail(), error_value, {
		log(error_value);
		return error_value;
	});
	Ok(())
}

The macro above expands to a simple match function:

let _ok_value = match a_function_which_may_fail() {
	Ok(v) => v,
	Err(error_value) => {
		log(error_value);
		return error_value;
	}
}

There are four functions with this syntax:

let ok_value = unwrap_ok_or!(function_returning_result, error_variable_name, code_to_run_on_error);

let error_value = unwrap_err_or!(function_returning_result, ok_variable_name, code_to_run_on_ok);

let some_value = unwrap_some_or!(function_returning_option, code_to_run_on_none);

let none_value = unwrap_none_or!(function_returning_option, some_variable_name, code_to_run_on_some);

No runtime deps