book icon indicating copy to clipboard operation
book copied to clipboard

Clarify some sentences that could cause misunderstanding in ch 17-02.

Open c0wjay opened this issue 3 years ago • 0 comments
trafficstars

When we use trait objects, Rust must use dynamic dispatch. The compiler doesn’t know all the types that might be used with the code that’s using trait objects, so it doesn’t know which method implemented on which type to call. Instead, at runtime, Rust uses the pointers inside the trait object to know which method to call. This lookup incurs a runtime cost that doesn’t occur with static dispatch. Dynamic dispatch also prevents the compiler from choosing to inline a method’s code, which in turn prevents some optimizations. However, we did get extra flexibility in the code that we wrote in Listing 17-5 and were able to support in Listing 17-9, so it’s a trade-off to consider.

URL to the section(s) of the book with this problem: https://doc.rust-lang.org/book/ch17-02-trait-objects.html#trait-objects-perform-dynamic-dispatch

Reference: https://oswalt.dev/2021/06/polymorphism-in-rust/

Description of the problem: According to the last paragraph of the book, It says "When we use trait objects, Rust must use dynamic dispatch." Reader may misunderstand that when they use trait objects, then Rust compiler always use dynamic dispatch - binding function at run-time.

However, according to reference that I attached above, you can see an example of a compiler using a static dispatch despite using an trait object.

Suggested fix: Shows two kinds of example - using trait & static dispatch or using trait & dynamic dispatch

or clarify the sentence.

c0wjay avatar Oct 30 '22 05:10 c0wjay