@StefanoD because I'm sending this struct as a command to implement, and based on command type it will contain different type of data, but I need to fix main command struct, so I can't use T
Didn't thought about that ! In terms of code it is better than my "non-functional" solution. But is it affects performance in Rust's implementation ?
For example in C++11 they have Lambda expressions for functional programming, but they affecting performance a lot.
Its hard to say with certainty (you should benchmark), but I doubt it will be significantly less performant. I'm guessing what you're doing now is something like this:
match self.code {
0 => match self.data.downcast_ref::<Foo>() { ... },
1 => match self.data.downcast_ref::<Bar>() { ... },
2 => match self.data.downcast_ref::<Baz>() { ... },
...
}
Each call therefore involves the match dispatch and then a downcast_ref. The downcast_ref is a virtual call. By using a boxed closure, you can just avoid the matching on self.code, and then you will have 1 virtual call. In other words, in the abstract it seems possibly more performant.
I don't know what the semantics of C++ lambdas are, but Rust's are a very efficient, first class part of the language. You should not shy away from using them.
In general, also, Any is almost never the right solution. It doesn't let the type system help you.