特征默认函数实现是否导致泛型代码泛滥?

时间:2020-07-19 05:48:55

标签: generics rust traits code-size

我偶然发现了this interesting code example

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

在C ++中,如果这是基类而不是特征,则call_foo_twice仅被编译一次,但是它将动态地将调用分派到foo,后者本身将被声明为虚拟的。 / p>

如果那些foo调用是在Rust中静态分派的,则表明call_foo_twice将为实现Bar的每个单一类型重新编译,因为每种类型都有其自己的唯一定义。 foo。这个对吗?对于我更喜欢​​减少编译时间而不是提高性能的情况,我应该使用一个惯用法吗?

0 个答案:

没有答案