Rust trait 有运行时开销吗?

use*_*855 0 traits dynamic-dispatch rust static-dispatch

如果我在下面的代码中创建c1类型Concrete1,是否有任何运行时开销?

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();
}
Run Code Online (Sandbox Code Playgroud)

这是否需要任何类型的 v 表查找或任何其他类型的开销?我想要一个特征,以便我可以在编译时强制执行Concrete1Concrete2实现相同的方法集。

我将静态选择在主程序中使用哪种具体类型;这两个实现的存在只是为了在需要时我可以使用 trait 的替代实现。

kmd*_*eko 5

如果具体类型是静态已知的,则使用静态分派。

如果具体类型未知(即 trait 对象:)&dyn ExampleTrait,则使用动态分派。

也可以看看: