Here is the version of apply that works for tuples with sizes from 1 to 6 (can be increased) ( Playground ):
fn main() { let add1 = |x| x + 1; let sum2 = ::std::ops::Add::add; let sum3 = |a, b, c| a + b + c; assert_eq!(apply(add1, (1,)), 2); assert_eq!(apply(sum2, (1, 2)), 3); assert_eq!(apply(sum3, (1, 2, 3)), 6); } #[inline(always)] pub fn apply<Fun, In, Out>(fun: Fun, params: In) -> Out where ApplyImpl: Apply<Fun, In, Out> { ApplyImpl::apply(fun, params) } pub trait Apply<Fun, In, Out> { fn apply(fun: Fun, params: In) -> Out; } pub struct ApplyImpl; macro_rules! impl_apply { () => (); ($A:ident, $($B:ident,)*) => ( impl_apply!{$($B,)*} impl<$A, $($B,)* Fun, Out> Apply<Fun, ($A, $($B),*), Out> for ApplyImpl where Fun: Fn($A, $($B),*) -> Out {
I am going to create a box for this. If I do, I will put the link here.
source share