#options #conditional #take #if

take-if

A tiny utility for conditionally taking the contents of an option

2 releases (1 stable)

1.0.0 May 2, 2020
0.1.0 May 2, 2020

#2092 in Rust patterns

22 downloads per month

MIT license

5KB

take-if

A tiny utility for conditionally taking the contents from an Option. See also Option::take.

use take_if::TakeIf;

let mut maybe_greeting = Some("Hello, World!");

if let Some(greeting) = maybe_greeting.take_if(|greeting| greeting.starts_with("Hello")) {
    println!(r#"Greeting {:?} starts with "Hello""#, greeting);
} else {
    println!(r#"There was no greeting, or it didn't start with "Hello""#);
}

Usage

Add take-if to your Cargo.toml:

[dependencies]
take-if = "1.0.0"

Import the TakeIf trait in your modules to add the take_if method to Option:

use take_if::TakeIf;

let taken = maybe_value.take_if(|value| value.id == 5);

lib.rs:

Conditionally take a value out of an option.

This crate adds a take_if extension method to Option which conditionally takes the value out of an option, leaving None in its place if the value was taken. The predicate function is only called if the option is Some, and receives a reference to the option's contents.

If you don't need to take the value conditionally, i.e. you always need to take the value, use Option::take instead.

Examples

use take_if::TakeIf;

let mut maybe_greeting = Some("Hello, World!");

if let Some(greeting) = maybe_greeting.take_if(|greeting| greeting.starts_with("Hello")) {
    println!(r#"Greeting {:?} starts with "Hello""#, greeting);
} else {
    println!(r#"There was no greeting, or it didn't start with "Hello""#);
}

No runtime deps