๐Ÿ“Rust: on-stack dynamic dispatch

source
On-Stack Dynamic Dispatch - Rust Design Patterns

Dynamic dispatch in Rust only works with trait references. However, the object must be allocated somewhere.

It is impossible to stack-allocate a dyn object because they are unsized. But it is possible to allocate uninitialized variables and store a reference to one of them.

use std::io;
use std::fs;

// These must live longer than `readable`, and thus are declared first:
let (mut stdin_read, mut file_read);

// We need to ascribe the type to get dynamic dispatch.
let readable: &mut dyn io::Read = if arg == "-" {
    stdin_read = io::stdin();
    &mut stdin_read
} else {
    file_read = fs::File::open(arg)?;
    &mut file_read
};

Rust requires initialization of variable before use, but that does not mean that every variable must be initialized. A variable can be uninitialized if it is not used.

Notes

Backlinks

โฆ
Want to receive my ๐Ÿ–‹ posts as I publish them?