[][src]Trait also::Also

pub trait Also {
    fn lets<R>(self, f: impl FnOnce(Self) -> R) -> R
    where
        Self: Sized
, { ... }
fn take_if<R, E>(
        self,
        f: impl FnOnce(&mut Self) -> Result<R, E>
    ) -> Result<Self, E>
    where
        Self: Sized
, { ... }
fn also<R>(self, f: impl FnOnce(&mut Self) -> R) -> Self
    where
        Self: Sized
, { ... } }

Provides Kotlin-esque helper functions for all types via a blanket impl, enabling easier function chaining patterns

let not_empty = ().lets(|_| "Hello, world!");
assert_eq!("Hello, world!", not_empty);

Provided methods

fn lets<R>(self, f: impl FnOnce(Self) -> R) -> R where
    Self: Sized

Calls a function with the receiver, and returns the result. Akin to Kotlin's let extension function

Examples

let x = "Hello, world!".lets(|x| x.len());
assert_eq!(13, x);

let x = "Hello, world!".to_string().lets(|mut x| {
    x.push('g');
    x.len()
});
assert_eq!(14, x);

fn take_if<R, E>(
    self,
    f: impl FnOnce(&mut Self) -> Result<R, E>
) -> Result<Self, E> where
    Self: Sized

Returns the receiver if the given function returns Ok, else forwards the Err. Akin to Kotlin's takeIf extension function

Examples

let x = "42".take_if(|x| u8::from_str_radix(x, 10));
assert_eq!(Ok("42"), x);

let x = "aa".take_if(|x| u8::from_str_radix(x, 10));
assert!(x.is_err());

fn also<R>(self, f: impl FnOnce(&mut Self) -> R) -> Self where
    Self: Sized

Calls a function with the receiver, and returns the receiver. Akin to Kotlin's also extension function

Examples

let x = "Hello".to_string().also(|x| x.push_str(", world!"));
assert_eq!("Hello, world!", x);
Loading content...

Implementors

impl<T> Also for T[src]

Loading content...