Compiler IQ: Used-unused variables (i.e. feature guarded)

Still not working full-time with Rust... so likely have forgotten something in the book.

Nonetheless, I am curious about whether I can say the compiler 'eliminates' the variable foo when feature fooable is inactive/unset, and is this the/a Rusty-way to avoid calling Some::foo() more than once:

fun fooable() {
    let foo: Option<_>;
        if cfg!(feature = "fooable") {
            foo = Some(Some::foo());
        } else {
            foo = None;
        }
        #[cfg(feature = "fooable")]
        {
            let b = Some::bar(&foo);
            // etc.
        }
        //more etc.
        #[cfg(feature = "fooable")]
        {
            let b = Some::bar(&foo);
            // etc.
        }
}

You should normally just rely on the optimizer (constant folding, control flow analysis, etc.) to remove unused variables and unreachable code in a release build.

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.