Attribute Macro derive_n_functor

Source
#[derive_n_functor]
Expand description

Generate a map function for a given type that maps across all its type parameters. i.e.

#[derive(...)]
// optional: setting a name for the type parameters, doesn't affect the structure
// of the data in any way, just the variable names.
#[derive_n_functor(B = second_type_param)]
// We can also choose a different map name, the default being `map`.
// This will recurse down to child elements without a custom `map_with` declaration.
// #[derive_n_functor(map_name = different_map)]
struct Data<A, B> {
    a: A,
    // The map_with argument is an arbitrary expression.
    #[map_with(Option::map)]
    b: Option<B>
}

Will generate a mapping function of the form: Data::map(self, map_a: impl Fn(A) -> A2, map_second_type_param: impl B -> B2) -> Data<A2, B2>.

See examples and use cargo-expand to see how different code generates.

Currently works with enums and structs.

Caveats:

  • Does not work with data structures that have lifetimes or constants in them at this time.
  • Does not currently work well with i.e. tuples where one of the types within is a type parameter. if you need to deal with this, write an external function that applies the mappings (see examples.)