I have an enum ABC
with 3 variants that share the same S
struct, therefore I want to call the same method on them with the same variables. I know I could implement a trait, but this is a simplification of an example where A
, B
and C
have other structs that make them different, but they share the same methods.
enum S{}
impl S{
pub fn do_something(&self, number: u8) -> Result<(),()>{
}
}
enum ABC{
A(S),
B(S),
C(S)
}
//This is my attempt, but I don't know how to match for closures
macro_rules! for_each_stack {
($self:ident: &ABC, $b:block) => {
match $self {
ABC::A(s) => $b(s),
ABC::B(s) => $b(s),
ABC::C(s) => $b(s),
}
}
}
impl ABC {
//I'm trying to substitute this:
pub fn do_something(&self, number: u8) {
match self {
ABC::A(s) => s.do_something(number),
ABC::B(s) => s.do_something(number),
ABC::C(s) => s.do_something(number),
}
}
//By this macro call
pub fn do_something2(&self, number: u8) {
for_each_stack!(self, |s| s.do_something(number))
}
}
I'm having difficulties matching the macro for the closure. How should I do that? I tried with a block but this wont work of course.
Look that I'm also forcing $self:ident: &ABC
so I can match over its variants.