Static and dynamic dispatch

Trait objects likewise have no statically known size in Rust. Trait objects are the mechanism by which Rust performs dynamic dispatch. Preferentially, Rust is a static dispatch language as there are increased opportunities for inlining and optimization—the compiler simply knows more. Consider the following code:

use std::ops::Add;

fn sd_add<T: Add<Output=T>>(x: T, y: T) -> T {
    x + y
}

fn main() {
    assert_eq!(48, sd_add(16 as u8, 32 as u8));
    assert_eq!(48, sd_add(16 as u64, 32 as u64));
}

Here, we define a function, sd_add<T: Add<Output=T>>(x: T, y: T) -> T. Rust, like C++, will perform monomorphization at compile time, emitting two sd_add functions, one for u8 and the other for u64. Like C++, this potentially increases ...

Get Hands-On Concurrency with Rust now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.