Do trait default function implementations cause code bloat the same way generics do?

123 Views Asked by At

I stumbled on this interesting code example:

trait Bar {
    fn foo(&mut self);
    fn call_foo_twice(&mut self) {
        self.foo(); // <-- this is statically dispatched
        self.foo();
    }
}

In C++, if this were a base class instead of a trait, call_foo_twice would only be compiled once, but it would dynamically dispatch the calls to foo, which itself would be declared virtual.

If those foo calls are statically dispatched in Rust, that suggests call_foo_twice is going to be recompiled for every single type that implements Bar because each type will have its own unique definition of foo. Is this correct? For instances where I prefer reducing compile time over increasing performance is there an idiom I should use instead?

0

There are 0 best solutions below