#options #result #tool

not-found-error

Convert Option to Result using convenient functions

11 releases

0.2.3 Sep 12, 2024
0.2.2 Sep 5, 2024
0.2.1 Aug 5, 2024
0.1.6 Jul 31, 2024

#519 in Rust patterns

Download history 708/week @ 2024-07-30 54/week @ 2024-08-06 144/week @ 2024-09-03 100/week @ 2024-09-10 17/week @ 2024-09-17 26/week @ 2024-09-24 24/week @ 2024-10-01

88 downloads per month

Apache-2.0 OR MIT

17KB
183 lines

Convert Option to Result

Build Documentation

Overview

// Convert Option<i32> to Result<i32, NotFoundError<i32>>

assert_eq!(Some(10).require(), Ok(10));

assert_eq!(None.require(), Err(NotFoundError::<i32>::new()));

This crate provides a generic NotFoundError<T> type and associated utilities for handling “not found” scenarios in a type-safe and ergonomic manner.

You can convert Option<T> to Result<T, NotFoundError<T> using require function or Require extension trait.

You can convert Option<T> to Result<T, NotFoundError<AnotherType> using not_found function or OkOrNotFound extension trait.

Features

  • Generic NotFoundError<T> type
  • Conversion functions and traits to transform Option<T> into Result<T, NotFoundError<T>>
  • Conversion functions and traits to transform Option<T> into Result<T, NotFoundError<AnotherType>>

Examples

use not_found_error::{NotFoundError, Require, locate, require};

// Using the `require` function
let item = require([1, 2, 3].into_iter().next());
assert_eq!(item, Ok(1));

// Using the `require` function
let item = require([].into_iter().next());
assert_eq!(item, Err(NotFoundError::<i32>::new()));

// Using the `require` extension method
let item = [1, 2, 3].into_iter().next().require();
assert_eq!(item, Ok(1));

// Using the `require` extension method
let item = [].into_iter().next().require();
assert_eq!(item, Err(NotFoundError::<i32>::new()));

// Try to find a number greater than 10 (which doesn't exist in our list)
let numbers = &[1, 2, 3];
let result = locate(numbers, |&&n| n == 0);
assert_eq!(result, Err(NotFoundError::new()));

Installation

cargo add not-found-error

Gratitude

Like the project? ⭐ Star this repo on GitHub!

License

Apache License 2.0 or MIT License at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

No runtime deps