Just came across the article On-Stack Dynamic Dispatch, the code sample as following:
use std::io;
use std::fs;
fn main() -> Result<(), Box<dyn std::error::Error>>
{
let arg = "-";
// 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
};
// Read from `readable` here.
Ok(())
}
I guess that the compiler is not able to determine at compile time which variable is initialized stdin_read
or file_read
, then it has allocate some flag in the generated machine code and do the bookkeeping in runtime, otherwise it does not know which variable to drop. What's the truth here ?