Rust變量綁定-範圍和陰影

範圍和陰影

變量綁定有一個範圍,並且被約束在一個塊中。塊是語句的集合括在大括號 {} 內,所以, 變量陰影 是被允許的。

fn main() {
// This binding lives in the main function
let long_lived_binding = 1;

// This is a block, and has a smaller scope than the main function
{
    // This binding only exists in this block
    let short\_lived\_binding = 2;

    println!("inner short: {}", short\_lived\_binding);

    // This binding \*shadows\* the outer one
    let long\_lived\_binding = 5\_f32;

    println!("inner long: {}", long\_lived\_binding);
}
// End of the block

// Error! \`short\_lived\_binding\` doesn't exist in this scope
println!("outer short: {}", short\_lived\_binding);
// FIXME ^ Comment out this line

println!("outer long: {}", long\_lived\_binding);

}

0 條評論,你可以發表評論,我們會進行改進
Comment author placeholder