Hacker News new | ask | show | jobs
by AnimalMuppet 118 days ago
I think the question is, do you know at compile time what the concrete type is? In situations where you do, use static. (I'm not sure I'd call that "polymorphism". If you know the static type it's just a function on a type, and who cares that other types have functions with the same name?) But if you don't know the concrete type at compile time, then you must use dynamic dispatch.

And you can use each approach with the same type at different points in the code - even for the same function. It just depends on you local knowledge of the concrete type.

2 comments

That's polymorhpism 101, and not quite what I was asking. From my understanding what Rust has is something different to what C++ is offering. In C++ you either opt-in for static- or dynamic-dispatch. In Rust it seems that you can mix both for the same type object and convert between the two during runtime. It seems that this is true according to the example from dminik from the comment above but the actual purpose is still not quite evident to me. It seems that it tries to solve the problem of excessive template instantiations, called as I can see monomorphizations in Rust. In C++ this is normally and mostly done through the linker optimizations which may suggest that Rust doesn't have them yet implemented or that there are more useful cases for it.
> It seems that it tries to solve the problem of excessive template instantiations

No, I don't think the way Rust implements dynamic dispatch has much, if anything, to do with trying to avoid code bloat. It's just a different way to implement dynamic dispatch with its own set of tradeoffs.

+1