0

Is there any runtime overhead if I create c1 of type Concrete1 in the code below?

pub trait ExampleTrait {
    fn foo(&self);
}

pub struct Concrete1 {}

impl ExampleTrait for Concrete1 {
    fn foo(&self) {}
}

pub struct Concrete2 {}

impl ExampleTrait for Concrete2 {
    fn foo(&self) {}
}

fn main() {
    let c1 = Concrete1 {};
    c1.foo();
}

Does this entail any sort of v-table lookup or any other kind of overhead? I want a trait so that I can enforce at compile time that both Concrete1 and Concrete2 implement the same set of methods.

I will statically choose which concrete type to use in the main program; the two implementations exist just so that I can use an alternative implementation of the trait if need arises.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user855
  • 19,048
  • 38
  • 98
  • 162
  • 1
    No. Dynamic dispatch is only [performed by trait objects](https://doc.rust-lang.org/book/ch17-02-trait-objects.html?highlight=dispatch#trait-objects-perform-dynamic-dispatch). – EvilTak Nov 04 '20 at 03:20

1 Answers1

5

If the concrete type is known statically, then static dispatch is used.

If the concrete type is not known (i.e. a trait object: &dyn ExampleTrait), then dynamic dispatch is used.

See also:

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
kmdreko
  • 42,554
  • 6
  • 57
  • 106