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:
- In Rust,
&mut Tcan be automatically dereferenced to&T - Avoids code duplication and simplifies the macro implementation
- Better performance by avoiding additional boxing operations
- 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 methodwhen<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