Hey there!
I'm trying to model something that usually, in OOP languages, is implemented using abstract class
and protected
visibility, and I'm not quite sure how to achieve kinda the same thing in Rust.
Let me explain.
The idea is to allow users to import a library by yours truly, in order to write some struct
s like so:
pub struct MyStruct {
some_value: i64
}
pub struct SomeValueUpdated(i64);
impl MyStruct {
pub fn update_some_value(self, new_value: i64) -> Self {
// NOTE: here we could do self.some_value = new_value,
// but the purpose is to avoid direct state change.
//
// The idea instead is to have something like:
self.record_that(SomeValueUpdated(new_value))
}
}
impl MyLibraryTrait for MyStruct {
type Action = SomeValueUpdated;
fn apply(self, action: Self::Action) -> Self {
// This is the actual state change happens:
self.some_value = action.0;
self
}
}
This record_that
method should be provided by said library, and that method should internally trigger a state change of Self
, and return the new Self
value.
In OOP languages you could do something like so:
abstract class MyLibraryTrait {
// here you can expect some state about what was recorded
abstract function apply(action)
protected function record_that(...) { ... }
}
class MyStruct extends Recorder {
private some_value;
public function apply(action) {
if action instanceof SomeValueUpdated {
this.some_value = action.new_value;
}
}
public function update_some_value(new_value) {
this.record_that(SomeValueUpdated(new_value));
}
}
Do you have any idea on how I would be able to model this in Rust?