macro_rules! impl_context_trait {
(
$(#[$ctx_meta:meta])*
context $ctx_name:ident<$t:ident> {
field $field:ident : $field_ty:ty
}
impl $trait_name:ident for WithContext<$t2:ident, $ctx_name2:ident<$t3:ident>> {
$(
fn $method:ident(&$self:ident $(, $arg:ident : $arg_ty:ty)* ) -> $ret:ty {
$($body:tt)*
}
)+
}
) => { ... };
}Expand description
Define a new context type and its trait implementation for WithContext.
This macro generates a context struct holding a function pointer and
implements the specified trait for WithContext<T, YourContext<T>>.
ยงExamples
use context_trait::{impl_context_trait, WithContext};
use std::fmt;
// Define a trait we want to contextualize
trait Summarize {
fn summarize(&self) -> String;
}
// Generate SummarizeContext and impl Summarize for WithContext
impl_context_trait! {
/// A context for custom summarization.
context SummarizeContext<T> {
field summarize_fn: fn(&T) -> String
}
impl Summarize for WithContext<T, SummarizeContext<T>> {
fn summarize(&self) -> String {
(self.ctx.summarize_fn)(&self.inner)
}
}
}
struct Article { title: String, body: String }
let ctx = SummarizeContext {
summarize_fn: |a: &Article| format!("{}...", &a.title),
};
let wrapped = WithContext {
inner: Article { title: "Hello".into(), body: "World".into() },
ctx,
};
assert_eq!(wrapped.summarize(), "Hello...");