macro_rules! impl_call {
    (
        $(#[$meta:meta])*
        fn $fn_kind:ident
        $( [ $( $fn_gen_params:tt )* ] )*
        ( $( $fn_params:tt )* )
        $( -> $ret_ty:ty )?
        $( where [ $( $where_preds:tt )* ] )*
        $body:block

    ) => { ... };
}
Available on crate feature callable only.
Expand description

This macro allows more ergonomically implementing the CallRef / CallMut / CallInto traits .

Examples

Implementing CallRef.


use core_extensions::{impl_call, CallExt};

struct Environment;

impl_call!{
    fn ref_call(self: Environment, printing: &str ) {
        println!("printing '{}'",printing);
    }
}

Environment.ref_call("what the ...");

Implementing CallMut.

Also demonstrates a polymorphic function, not possible in Rust closures yet.

use core_extensions::{impl_call, AsPhantomData, CallExt};

use std::marker::PhantomData;

struct Environment{
   i: u16,
}

impl_call!{
   // The PhantomData parameter is necessary because closures can't return a generic type
   // that doesn't appear in the parameter.
   fn mut_call[T](self: Environment, _a: PhantomData<T>) -> T
   where [ u16: Into<T>, ]
   {
       self.i += 1;
       self.i.into()
   }
}

let mut env = Environment{i:0};
assert_eq!(env.mut_call(u16::PHANTOM), 1);
assert_eq!(env.mut_call(u32::PHANTOM), 2);

Implementing CallInto.

use core_extensions::{impl_call, CallExt};

struct Environment<T>(T);

impl_call!{
    fn into_call[T](self: Environment<T>)->T{
        self.0
    }
}


let env = Environment("hello");
assert_eq!(env.into_call(()), "hello");

Syntax

$( ... )* means repeated 0 or more times.

$( ... )+ means repeated 1 or more times.

$( ... )? means that this is optional.

< ... > is a variable,replaced with whatever it refers to.


$(#[$meta:meta])*

// <fn_method_name> is one of (into_call|mut_call|ref_call),determining which trait
// is implemented.
fn <fn_method_name>

// Optionally declares the generic parameters of the function.
$( [ $( <generic_parameter> )* ] )?

// <self_type> is the type of the closure environment,which is implementing the Call traits.
// <function_parameter> are optional function parameters.
(   
    self: <self_type>
    $(, <function_parameter> )*
    $(,)?
)

//<return_tyoe> optional return type,defaults to '()'.
$( -> <return_type> )?

// An optional where clause,
// all tokens inside `[...]` get copied directly to the where clause of the impl.
$( where [ $( <where_predicates> )* ] )*

{
    // The definition of the function
    <function_definition>
}