Ambassador - Delegate trait implementations via procedural macros
Delegating the implementation of traits to enum variants or fields of a struct normally requires a lot of boilerplate code. Ambassador is an attempt to eliminate that boilerplate by deriving the delegating trait implementation via procedural macros.
The minimum supported Rust version is 1.40.0.
Installation
cargo add ambassador
General Usage
#[delegatable_trait]
First we need to make our trait available for delegation by adding a #[delegatable_trait]
attribute to it (this also makes your trait delegatable in other crates):
use delegatable_trait;
// <-------
#[derive(Delegate)]
& #[delegate(Trait)]
Now we can delegate the implementation of our trait to a struct field/enum variants by adding #[derive(Delegate)]
and its associated attribute #[delegate(Trait)]
to it:
use Delegate;
;
// <-------
// <-------- Delegate implementation of Shout to struct field
;
#[delegate(..., target = "foo")]
- target
key
For structs with multiple fields, the field that should act as delegation target can be specified via the target
key:
// <-------- Delegate implementation of Shout to struct field .foo
This also works for tuple structs with multiple fields, by using their index as a target key:
// <-------- Delegate implementation of Shout to second field of type Dog
;
For remote traits: #[delegatable_trait_remote]
If you want to make an existing trait that lives outside you crate available for delegation, you can do so by copy-pasting it's signature into your code and using the #[delegatable_trait_remote]
attribute (see full code sample):
use delegatable_trait_remote;
use Display;
// <-------- Delegate implementation of Display to struct field
;
Usage Examples
In this example we have a trait Shout
that is implemented for both Cat
and Dog
.
Delegate to enum variants
We now add an Animal
enum and add a delegated trait implementation for Shout
,
that calls the respective implementations of the enum variants:
use ;
;
;
Delegate to tuple struct field
Delegating a trait implementation for a tuple struct (only single-field tuples supported for now), for e.g. a newtype pattern.
use ;
;
;
Delegate to struct field
Delegating a trait implementation for a normal struct
use ;
;