๐Rust: on-stack dynamic dispatch
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
The compiler is required to call
drop
at the end of the function body, but only for initialized variables. This requires the compiler to either split the code paths or generate flags that store initialization status.
Backlinks
- ๐ Rust