Crust of Rust: Dispatch and Fat Pointers

Jon Gjengset · 107K views · 2021 · 2:12:52

Open on YouTube

C, C++, Rust, Go & systems languagesProgramming language designtutorial

Why Stack Overflow recommends it

Stack Overflow users link it when answering questions about trait objects, dyn versus generic type parameters, and converting between static and dynamic dispatch in Rust.

Recommended by 1 people across 1 different months, 2021 to 2021.

What it is

A 2h12m Crust of Rust livestream by Jon Gjengset on static versus dynamic dispatch in Rust. It covers generics and monomorphization, trait objects, the Sized trait, vtables, object safety limitations and dynamically sized types, and closes with a Q&A.

What people said

Recommends battlmonstr · 2021-12 · Stack Overflow · on “expected trait object `dyn Responsability`, found type parameter `T`”

dyn I and <T> where T: I are different types in Rust, so the compiler complains since there's no implicit conversion. T is a concrete type determined at compile time. dyn I it is a "trait object", it is dynamic, and concrete type is unknown, but sort of carried within. A good video [this video] on the topic. Conversion from <T> where T: I to dyn I is not free, it has a runtime cost, so has to be explicit with the Rust's philosophy. The code could be fixed by using Vec<Box<dyn Responsability>> in all places. It will also allow you passing arbitrary types to new() , which is probably what you want, because Vec<T> has to contain objects of the same type (remember that this type is determined at comp

Cites user4815162342 · 2021-05 · Stack Overflow · on “Transform static dispatch code into dynamic dispatch”

@ilmoi Here [LINK] is a modified version that compiles. The `as _` converts `Box ` to `Box `, which is important because `largest_dyn()` expects a slice of those. (`_` in `Vec ` tells the compiler to infer the type.) You can't send strings/ints to `largest_dyn()` the way you could to the generic version, you need to convert them to some form of reference (i.e. `&`, `Box`, `Rc`, or `Arc`). For more information see e.g. this stream [this video] .

Cites Clark McCauley · 2021-10 · Stack Overflow · on “Storing different implementations of a trait in a HashMap”

I've come up against an interesting issue. Here is a playground link [LINK] I'm trying to write a flexible task executor that is driven by providing JSON objects such as the following. { "task_type": "foobar", "payload": {} } The task executor would use the task_type to determine which executor to call and then pass the associated payload. Most of my types support generics because different task_type s would support different payload s. The way I've chosen to solve this problem is by creating a trait Task and a single implementor (for now) called RegisteredTask which essentially just calls a function pointer. My only compilation problem is the following which indicates that I would need to r