Macro dilib::add_singleton_trait
source · [−]macro_rules! add_singleton_trait {
($container:ident, $trait_type:ident $(<$($generic:ident),+>)? => $impl_expr:expr) => { ... };
($container:ident, $name:literal, $trait_type:ident $(<$($generic:ident),+>)? => $impl_expr:expr) => { ... };
($container:ident, $trait_type:ident $(<$($generic:ident),+>)? => { $impl_expr:expr }) => { ... };
($container:ident, $name:literal, $trait_type:ident $(<$($generic:ident),+>)? => { $impl_expr:expr }) => { ... };
($container:ident, $trait_type:ident $(<$($generic:ident),+>)? @ $inject_type:ty) => { ... };
($container:ident, $name:literal, $trait_type:ident $(<$($generic:ident),+>)? @ $inject_type:ty) => { ... };
}Expand description
Helper macro to bind a trait to it’s implementation in a Container as a singleton.
Overloads
add_singleton_trait!(container, name, trait => implementation)
add_singleton_trait!(container, trait => implementation)
add_singleton_trait!(container, name, trait @ Inject)
add_singleton_trait!(container, trait @ Inject)
Params
container: identifier of the container to add the implementation.name: optional name to store the provider.trait: the type of the trait.implementation: the implementation of the trait.Inject: a struct that implementsInject.
Examples
Basic usage
#[macro_use]
extern crate dilib;
use dilib::*;
trait Greet {
fn greet(&self) -> &str;
}
struct HelloWorld;
impl Greet for HelloWorld {
fn greet(&self) -> &'static str {
"hello world"
}
}
fn main() {
let mut container = Container::new();
add_singleton_trait!(container, Greet => HelloWorld).unwrap();
let greet = get_singleton_trait!(container, Greet).unwrap();
assert_eq!(greet.greet(), "hello world");
}With named trait
#[macro_use]
extern crate dilib;
use dilib::*;
trait BinaryOp {
fn calc(&self, lhs: i32, rhs: i32) -> i32;
}
struct Sum;
struct Prod;
impl BinaryOp for Sum {
fn calc(&self, lhs: i32, rhs: i32) -> i32 { lhs + rhs }
}
impl BinaryOp for Prod {
fn calc(&self, lhs: i32, rhs: i32) -> i32 { lhs * rhs }
}
fn main() {
let mut container = Container::new();
add_singleton_trait!(container, "sum", BinaryOp => Sum).unwrap();
add_singleton_trait!(container, "prod", BinaryOp => Prod).unwrap();
let sum = get_singleton_trait!(container, BinaryOp, "sum").unwrap();
let prod = get_singleton_trait!(container, BinaryOp, "prod").unwrap();
assert_eq!(5, sum.calc(2, 3));
assert_eq!(6, prod.calc(3, 2));
}