Module stackbox::dyn_traits[][src]

Hand-rolled implementations of pervasive StackBox<dyn …> types.

Explanation

Given the baked-into-the-language nature of trait objects, receiver types, and auto-generated vtables, things like StackBox<'_, dyn Any> & co. Do Not Work™.

So we need to hand-roll those, and this is what this module is about.


Currently, only basic FnOnce() signatures and Any are supported, since they are the only traits in the standard library with (part of) their API consuming ownership of the trait object, leading to &'_ mut dyn … not sufficing (c.f., the classic “wrap that FnOnce() into an Option to get an FnMut() you can thus type-erase with &mut dyn FnMut()”; which exposes the pattern to runtime panics if the consumer of the &mut dyn FnMut() calls it multiple times).

Creation

The StackBoxDyn… family of types is created using the .into_dyn() method. Such method is based on an internal trait, that defines the vtable and usability of these wrapper types, but the next section shows how downstream users may add implementations of this trait.

Custom-defined StackBoxDyn…s

These can now be created thanks to the powerful custom_dyn! macro.

Modules

any

Since StackBox<'_, dyn Any…> does not auto-implement Any…, we need to do it manually.

fn_once

Since StackBox<'_, dyn FnOnce…> does not auto-implement FnOnce…, we need to do it manually.