Shadowing Rebinds Within Blocks

Reuse a name with a new type through shadowing, contrast it with mut, and let block expressions produce values like if/else chains.

RustData Integrity

Code

rustsnippet
31 lines
fn main() {
    // shadowing:同名重新绑定,类型可以彻底改变
    let raw = "  42 ";
    let trimmed = raw.trim();
    let raw = trimmed.parse::<i32>().unwrap();
    println!("parsed: {raw}"); // raw 现在是 i32,不再是 &str

    // 与 mut 不同:shadowing 产生新绑定,旧值不动
    let unit = "px";
    let unit = unit.len();
    println!("unit chars: {unit}");

    // 块是表达式:最后一条表达式就是块的值
    let tier = {
        let score = 87;
        if score >= 90 {
            "gold"
        } else if score >= 80 {
            "silver"
        } else {
            "bronze"
        }
    };
    println!("tier: {tier}");

    // 每轮循环重新 shadowing 转换
    for input in ["1", "x", "3"] {
        let value = input.parse::<i32>().unwrap_or(-1);
        println!("{input} -> {value}");
    }
}

How it works

Shadowing Rebinds Within Blocks is built around the function main.

Repetition is confined to for input in ["1", "x", "3"] — the rest of the file is straight-line.

Using it

Running the file prints labeled results such as parsed:, unit chars:, tier: — each operation’s effect is visible in the output.

Key statements

let value = input.parse::<i32>().unwrap_or(-1);
let raw = trimmed.parse::<i32>().unwrap();

Interactive Tools for This Topic

FAQ

What does Shadowing Rebinds Within Blocks print when run?
Run it as a complete program — the output lines carry labels such as `parsed:`, `unit chars:`, `tier:`.