2 stable releases
1.0.1 | May 14, 2020 |
---|---|
1.0.0 | Dec 20, 2019 |
#2138 in Rust patterns
28 downloads per month
Used in rubot
5KB
Tapir
A simple rust library adding tapping functionality to all types.
The tap
operation takes full ownership of a variable, calls the given function with a mutable
reference to the given variable and then returns full ownership of it.
This allows for easy mutation without having to declare the variable as mutable.
This library is partially inspired by tap-rs.
Examples
fn get_unsorted_values() -> Vec<u32> {
vec![42, 7, 1337, 69]
}
fn use_sorted_values(values: &[u32]) {
assert_eq!(&[7, 42, 69, 1337], values);
}
// without tap one often needs mutable variables
let mut old = get_unsorted_values();
old.sort();
use_sorted_values(&old);
// using tap, this can be simplified
use tapir::Tap;
let tapped = get_unsorted_values().tap(|v| v.sort());
use_sorted_values(&tapped);
lib.rs
:
A crate exposing the Tap
trait, which makes method chaining easier.
Check out Tap
for a more detailed documentation.
Examples
use tapir::Tap;
fn smallest_factor(x: u32) -> u32 {
for i in 2..x {
if x % i == 0 {
return i;
}
}
x
}
let smallest_factors: Vec<u32> = (2..25).map(smallest_factor).collect();
let unique_primes = smallest_factors.tap(|v| v.sort()).tap(Vec::dedup);
assert_eq!(unique_primes, [2, 3, 5, 7, 11, 13, 17, 19, 23]);