The final code worked with me is as per this playground:
//#[derive(Debug)]
pub struct Counter {
count: i32,
}
impl std::fmt::Debug for Counter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Counter `count` is: {}", self.count)
}
}
trait EventEmitter {
fn square(&mut self);
fn increase(&mut self, amount: i32);
fn decrease(&mut self, amount: i32);
fn change_by(&mut self, amount: i32);
}
impl EventEmitter for Counter {
fn square(&mut self) {
self.count = self.count.pow(2);
Self::on_squared();
}
fn increase(&mut self, amount: i32) {
self.count += amount;
Self::on_increased(amount);
}
fn decrease(&mut self, amount: i32) {
let initial_value = self.count;
self.count -= amount;
Self::on_decreased(Self {count: initial_value}, amount);
}
fn change_by(&mut self, amount: i32) {
let initial_value = self.count;
self.count += amount;
match amount {
x if x > 0 => Self::on_increased(amount),
x if x < 0 => Self::on_decreased(Self {count: initial_value}, amount.abs()),
_ => println!("No changes")
}
}
}
trait EventListener {
fn on_squared() {
println!("Counter squared")
}
fn on_increased(amount: i32) {
println!("Counter increased by {}", amount)
}
fn on_decreased(self, amount: i32);
}
impl EventListener for Counter {
fn on_decreased(self, amount: i32) {
println!("Counter reduced from {} to {}", &self.count, &self.count - amount)
}
}
fn main() {
let mut x = Counter { count: 5 };
println!("Counter started at: {:#?}", x.count);
x.square();
println!("{:?}", x);
x.increase(3);
println!("{:?}", x);
x.decrease(2);
println!("{:?}", x);
x.change_by(-1);
println!("{:?}", x);
}
And got the below output:
Counter started at: 5
Counter squared
Counter `count` is: 25
Counter increased by 3
Counter `count` is: 28
Counter reduced from 28 to 26
Counter `count` is: 26
Counter reduced from 26 to 25
Counter `count` is: 25