impl_scope!() { /* proc-macro */ }
Expand description

Implementation scope

Supports impl Self syntax.

Also supports struct field assignment syntax for Default: see impl_default.

Caveat: rustfmt will not format contents (see rustfmt#5254).

Syntax

ImplScope :
   impl_scope! { ScopeItem ItemImpl * }

ScopeItem :
   ItemEnum | ItemStruct | ItemType | ItemUnion

The result looks a little like a module containing a single type definition plus its implementations, but is injected into the parent module.

Implementations must target the type defined at the start of the scope. A special syntax for the target type, Self, is added:

ScopeImplItem :
   impl GenericParams? ForTrait? ScopeImplTarget WhereClause? {       InnerAttribute*       AssociatedItem*    }

ScopeImplTarget :
   Self | TypeName GenericParams?

That is, implementations may take one of two forms:

  • impl MyType { ... }
  • impl Self { ... }

Generic parameters from the type are included automatically, with bounds as defined on the type. Additional generic parameters and an additional where clause are supported (generic parameter lists and bounds are merged).

Example

use impl_tools::impl_scope;
use std::ops::Add;

impl_scope! {
    struct Pair<T>(T, T);

    impl Self where T: Clone + Add {
        fn sum(&self) -> <T as Add>::Output {
            self.0.clone().add(self.1.clone())
        }
    }
}