Rust-Dynamic -Dispatch


I want to understand dynamic dispatch. It is said that if the compiler cannot determine the
which method to be called, then the compiler emit code to determine the function during runtime.

My questions are

  1. Whether the following code compilation will result in dynamic dispatch ?.

  2. As the code is very clear in calling find_area(&r0) and find_area(&c0) ,
    why not Rust compiler prefers static dispatching.

  3. Basically what determines which method of dispatching ?

  4. whether "dyn" keyword is an indication that dynamic dispatching to be supported ?


trait Shape {
    fn area(&self)->f64 ;

struct Rect { x: f64, y:f64}
struct Circle{ r: f64}

impl Shape for Rect {

          fn area(&self) ->f64 {
           self.x * self.y

impl Shape for Circle {
  fn area(&self) ->f64 {
           3.14 * self.r * self.r

fn main()
   let r0 : Rect = Rect { x:10.1, y: 20.2};
   let c0 : Circle = Circle{r:5.1};


fn get_area ( i : & dyn Shape)
println!("Area is {}", i.area());
1 Like

Please try to run rustfmt on code examples. You can even do this online in the playground (under TOOLS).

To give a short answer to your question: Without dyn there will be no dynamic dispatch happening. With dyn, you will usually get dynamic dispatch unless the compiler can optimize it away again. This (optimization) can happen in your example.

For example the movabsq $4641382332157803888, %rax mentions the value

204.01999999999998 (coded as f64)

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.