devela::all

Trait Hook

Source
pub trait Hook: Sized {
    // Provided methods
    fn hook_ref<F>(self, f: F) -> Self
       where F: FnOnce(&Self) { ... }
    fn hook_mut<F>(self, f: F) -> Self
       where F: FnOnce(&mut Self) { ... }
}
Expand description

Allows attaching operations or side effects to a value without breaking its flow.

Use Hook when you want to inspect, log, or modify the value in-place without directly returning a new result from the function.

Useful for when a method doesn’t return the receiver but you want to apply several of them to the object.

It assumes that each function in the chain modifies the value by exclusive reference and returns the modified value.

§Examples

use devela::Hook;

let v = vec![3, 2, 1, 5]
    .hook_mut(|v| v.sort())
    .hook_ref(|v| assert_eq![v, &[1, 2, 3, 5]])
    .hook_mut(|v| v.push(7));
assert_eq![v, vec![1, 2, 3, 5, 7]];

See also the Chain trait.

Provided Methods§

Source

fn hook_ref<F>(self, f: F) -> Self
where F: FnOnce(&Self),

Applies a function which takes the parameter by shared reference, and then returns the (possibly) modified owned value.

Similar to chain_ref, but instead of returning self directly from f, since it has a different signature, returns it indirectly.

Source

fn hook_mut<F>(self, f: F) -> Self
where F: FnOnce(&mut Self),

Applies a function which takes the parameter by exclusive reference, and then returns the (possibly) modified owned value.

Similar to chain_mut, but instead of returning self directly from f, since it has a different signature, returns it indirectly.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<T: Sized> Hook for T