impl_fn_ops_trait

Macro impl_fn_ops_trait 

Source
macro_rules! impl_fn_ops_trait {
    (
        ($($fn_signature:tt)+),
        $trait_name:ident,
        $box_type:ident,
        $chained_function_trait:ident,
        $conditional_type:ident
    ) => { ... };
}
Expand description

Generate extension traits and implementations for closure types

This macro generates an extension trait that provides composition methods (and_then, when) for closures implementing the specified closure trait, without requiring explicit wrapping.

§Unified Implementation Strategy

The macro uses a unified implementation approach, passing intermediate results using mutable references (&mut). This is because:

  1. In Rust, &mut T can be automatically dereferenced to &T
  2. Avoids code duplication and simplifies the macro implementation
  3. Better performance by avoiding additional boxing operations
  4. Uses #[allow(unused_mut)] to suppress unnecessary mutability warnings

§Parameters

  • $fn_signature - Closure signature (in parentheses, without constraints)
  • $trait_name - Name of the extension trait
  • $box_type - Box wrapper type
  • $chained_function_trait - The name of the function trait that chained after the execution of this function (e.g., Function, BiFunction)
  • $conditional_type - Conditional function type

§Generated Code

Generates a trait definition and a blanket implementation, containing:

  • and_then<S, F> - Chain composition method
  • when<P> - Conditional execution method

§Examples

// Fn(&T) -> R version
impl_fn_ops_trait!(
    (Fn(&T) -> R),
    FnFunctionOps,
    BoxFunction,
    Function,
    BoxConditionalFunction
);

// FnMut(&T) -> R version
impl_fn_ops_trait!(
    (FnMut(&T) -> R),
    FnStatefulFunctionOps,
    BoxStatefulFunction,
    StatefulFunction,
    BoxConditionalStatefulFunction
);

// FnMut(&mut T) -> R version (consuming functions)
impl_fn_ops_trait!(
    (FnMut(&mut T) -> R),
    FnMutatingFunctionOps,
    BoxMutatingFunction,
    MutatingFunction,
    BoxConditionalMutatingFunction
);

§Author

Haixing Hu