pub trait StateField:
Send
+ Sync
+ Debug {
type Value: Resource;
// Required methods
fn init<'life0, 'life1, 'life2, 'async_trait>(
&'life0 self,
config: &'life1 StateConfig,
instance: &'life2 State,
) -> Pin<Box<dyn Future<Output = Arc<Self::Value>> + Send + 'async_trait>>
where Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
'life2: 'async_trait;
fn apply<'life0, 'life1, 'life2, 'life3, 'async_trait>(
&'life0 self,
tr: &'life1 Transaction,
value: Arc<Self::Value>,
old_state: &'life2 State,
new_state: &'life3 State,
) -> Pin<Box<dyn Future<Output = Arc<Self::Value>> + Send + 'async_trait>>
where Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
'life2: 'async_trait,
'life3: 'async_trait;
// Provided methods
fn serialize(&self, _value: &Arc<Self::Value>) -> Option<Vec<u8>> { ... }
fn deserialize(&self, _data: &[u8]) -> Option<Arc<Self::Value>> { ... }
}Expand description
PluginTrait实现一个 default 实现 状态字段特征 使用关联类型保持类型信息,提供类型安全的插件状态管理
§优势
- ✅ 编译期类型检查,无需运行时 downcast
- ✅ 更好的性能和代码可读性
- ✅ IDE 支持更好的自动补全
§示例
ⓘ
#[derive(Debug)]
struct MyValue {
count: u32,
}
impl Resource for MyValue {}
#[derive(Debug)]
struct MyStateField;
#[async_trait]
impl StateField for MyStateField {
type Value = MyValue;
async fn init(&self, _config: &StateConfig, _state: &State) -> Arc<MyValue> {
Arc::new(MyValue { count: 0 })
}
async fn apply(&self, _tr: &Transaction, value: Arc<MyValue>,
_old: &State, _new: &State) -> Arc<MyValue> {
// ✅ 类型安全,无需 downcast
Arc::new(MyValue { count: value.count + 1 })
}
}Required Associated Types§
Required Methods§
Sourcefn init<'life0, 'life1, 'life2, 'async_trait>(
&'life0 self,
config: &'life1 StateConfig,
instance: &'life2 State,
) -> Pin<Box<dyn Future<Output = Arc<Self::Value>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
'life2: 'async_trait,
fn init<'life0, 'life1, 'life2, 'async_trait>(
&'life0 self,
config: &'life1 StateConfig,
instance: &'life2 State,
) -> Pin<Box<dyn Future<Output = Arc<Self::Value>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
'life2: 'async_trait,
初始化插件状态
Sourcefn apply<'life0, 'life1, 'life2, 'life3, 'async_trait>(
&'life0 self,
tr: &'life1 Transaction,
value: Arc<Self::Value>,
old_state: &'life2 State,
new_state: &'life3 State,
) -> Pin<Box<dyn Future<Output = Arc<Self::Value>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
'life2: 'async_trait,
'life3: 'async_trait,
fn apply<'life0, 'life1, 'life2, 'life3, 'async_trait>(
&'life0 self,
tr: &'life1 Transaction,
value: Arc<Self::Value>,
old_state: &'life2 State,
new_state: &'life3 State,
) -> Pin<Box<dyn Future<Output = Arc<Self::Value>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
'life2: 'async_trait,
'life3: 'async_trait,
应用状态变更 根据事务内容更新插件状态