1 个不稳定版本
0.1.0 | 2023年7月7日 |
---|
#1333 在 过程宏
36KB
675 行
dep-inj
更易于依赖注入的工具。
示例
当您编写一个组件(此处命名为 OddState
)需要从其他crate注入一些依赖(此处命名为 Even
)时,dep_inj
可以帮助您。
//! odd component implementation
use dep_inj::DepInj;
#[derive(Default, DepInj)]
// to generator `OddProxy`
#[target(OddProxy)]
pub struct OddState {
count: usize,
}
// `OddState` provides `Odd`
impl<Deps> Odd for OddProxy<Deps>
where
// `is_odd` depends on `Even`
Deps: Even
{
fn is_odd(&mut self, n: u64) -> bool {
// `OddProxy` can be deref to `OddState`
self.count += 1;
(n == 1) || self
.prj_ref_mut()
// `OddProxy` can be projected to its dependency `Even`
// where
// ```
// trait Even {
// fn is_even(&mut self, n: u64) -> bool;
// }
// ```
.is_even(n)
}
}
并且您可以在顶级crate中注入这个依赖
#[derive(Default)]
struct GlobalState {
odd_state: OddState,
even_state: EvenState,
}
// boilerplate
// `impl AsRef<OddState> for GlobalState`
// `impl AsMut<OddState> for GlobalState`
// `impl AsRef<EvenState> for GlobalState`
// `impl AsMut<EvenState> for GlobalState`
impl Even for GlobalState {
fn is_even(&mut self, n: u64) -> bool {
// inject `GlobalState` which is impl `Odd` for `EvenState` component
EvenProxy::inj_ref_mut(self).is_even(n)
}
}
impl Odd for GlobalState {
fn is_odd(&mut self, n: u64) -> bool {
// inject `GlobalState` which is impl `Even` for `OddState` component
OddProxy::inj_ref_mut(self).is_odd(n)
}
}
fn main() {
let mut state = GlobalState::default();
assert!(state.is_odd(11));
}
更多信息请查看 在Rust组件接口调用中探索设计模式
依赖
~1.5MB
~36K SLoC