On-Stack Dynamic Dispatch: How rust drops unintialized variable

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.


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 ?

The compiler will use introduce a boolean variable to remember whether they should be dropped.


Once upon a time, all types that implemented Drop had an implicit drop flag embedded to track that state. You can read about how that was removed in RFC 320:


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.