Like C++, dynamic dispatch is achieved in Rust though a table of function pointers (described here in the rust docs). Given that rust is still a somewhat young language, I could appreciate why the developers might not want to introduce that complexity immediately (being stuck with a poor design forever would be a high cost for little reward), but I wanted to work out exactly how such a system might work (or not work). I would expect the object to have multiple vpointers for each 'base', and do dispatch through the appropriate one. In my mind, a trait object with multiple bounds would be analogous to multiple inheritance in C++. This fails with the the following error: error: only the builtin traits can be used as closure or object boundsĪnd I found this surprising. However, things break down when you try to add an additional trait to the trait object bounds like: You can iterate over the vector of subjects and call run or walk as you would expect. Suppose I want to create a struct CloningLab that contains a vector of trait objects (in this case, Mammal):
My real motivation for taking a closer look at dynamic dispatch can be seen in the following code snippet. With that out of the way, lets get started. Let me preface this by saying that I am a novice in the world of rust (though I'm liking things so far!), so if I make technical mistakes please let me know and I will try to correct them. Menu Exploring Dynamic Dispatch in Rust 07 March 2017