简体   繁体   中英

Do Rust traits have runtime overhead?

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.

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

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

See also:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM