将OOP观察者模式移植到Rust时的问题与实现困惑
把SDK从Java/Go移植到Rust的问题与优化思路
背景
我正在将一款SDK从Java和Go移植到Rust。原SDK通过模板自动生成OOP(Java)或基于反射(Go)的样板代码,希望在Rust中实现类似的用户体验:用户只需编写业务逻辑,底层机制自动运行。
自动生成的样板代码
trait RPC { fn decode(&self, frame: &Frame) -> (); fn execute(&self) -> (); } struct MyRPC{ decoded: String } impl RPC for MyRPC { // decode和execute方法的默认实现 }
用户预期的业务逻辑编写方式
用户只需引入自动生成的代码,然后重写execute方法即可:
include("autogeneratedCode") impl MyRPC { fn execute(&self){ // 使用&self.decoded处理业务逻辑 } }
观察者模式调用代码(当前存在问题)
let subscribers: HashMap<String, Box<dyn RPC>> pub fn publish(&self, frame: &Frame) -> () { for subscriber in self.subscribers.iter() { let mut cloned_subscriber = subscriber.1.clone(); // <<1 cloned_subscriber.parse(frame); // <<2 cloned_subscriber.execute(); // <<3 } }
当前遇到的问题
- 编译警告:
variable does not need to be mutable Note:#[warn(unused_mut)]on by default Help: remove thismut.,推测是subscriber.1.clone()返回的是Box<dyn RPC>,作为值无需可变修饰 - 编译错误:
cannot borrow**cloned_subscriberas mutable, as it is behind a&reference [E0596]cloned_subscriberis a&reference, so the data it refers to cannot be borrowed as mutable. - 逻辑问题:执行时调用的是
trait RPC中的默认execute实现,而非用户编写的MyRPC自定义版本
疑问
感觉自己在强行让Rust适配OOP思路,这可能是问题根源。是否应该采用更符合Rust风格的实现方式?我很喜欢Go/Java版本的模式——用户只需编写execute函数,底层机制自动运行,但这种模式在Rust中是否可行?
内容的提问来源于stack exchange,提问作者rsan
相关产品推荐
相关产品推荐

