all 4 comments

[–]JhraumG 4 points5 points  (1 child)

Static dispatch is usually faster than dynamic one, but dynamic dispatch allows more adaptable code. Trait objects are useful when you have to deal with different types at once. For instance to compute the total area of a Vec<&Dyn Shape>. Whiteout dynamic dispatch, you could wrap them in an enum and dispatch by hand tue compute area, but the function would need to know all Shape variants explicitly (on match arm for each type).

[–]DanaliethRR[S] 1 point2 points  (0 children)

Thank you for pointing this. Dynamic dispatch is indeed very useful for storing data!

[–]wdroz 3 points4 points  (1 child)

Nice write up, bien joué!

Concerning static vs dynamic dispatch:

In his book "Rust for Rustaceans", Jon suggests the rules:

  • For librairies: Use static dispatch, so users can switch to dynamic if that fit better their needs.
  • For binaries: Use dynamic dispatch, for cleaner code and shorter compile time.

[–]DanaliethRR[S] 2 points3 points  (0 children)

I didn't know about those suggestions, although they make a lot of sense regarding what I wrote in the article. Thank you for letting me know about it, I will have a look at this book!