Rust 实现 Custom Events
本文设计了一个比较巧妙的 Events 模式, 不由地让人想起 Qt
的 signal
.
下面是核心代码以及使用例子. 具体更多细节可以参阅原文.
trait Sig {
type Data;
type Receiver: Rec;
fn emit(&self, data: Self::Data);
fn conn(&mut self) -> Self::Receiver;
fn disc(&mut self, i: usize);
}
trait Rec {
type Data;
fn on_emit(self, data: Self::Data);
fn get_id(&self) -> usize;
}
macro_rules! def_signal{
// ...
}
// 使用例子
struct MySigData {
num: i32,
}
fn main() {
def_signal!(
MySig, // Signal 名字
MyRec, // Receiver 名字
NySigData, // 预定义的数据类型
|this: MyRec, data: MySigData| { // 逻辑
println!("MySig receriver R{} - num: {}", this.id, data.num);
}
)
let mut ms2 = MySig::new();
let r1 = ms2.conn();
let r2 = ms2.conn();
ms2.emit(MySigData{ num: 3})