Static and dynamic dispatch
Our function sqroot
from the previous section is generic and works for any Float
type. The compiler creates a different executable sqroot
method for any type it is supposed to work with, in this case the f32
and f64
type. Rust applies this mechanism when a function call is polymorphic, that is when a function can accept arguments of different type. This is called static dispatch (also called compile-time polymorphism) and there is no runtime overhead involved. This is in contrast to how Java interfaces work, where the dispatching is done dynamically in runtime by the JVM. However Rust also has a form of dynamic dispatch (also called runtime polymorphism), using so called trait objects.
For an example of static and dynamic dispatch, see the following code snippet:
// see code in Chapter 6/code/dispatch.rs struct Circle; struct Triangle; trait Figure { fn print(&self); } impl Figure for Circle { fn print(&self) { println!("Circle...