官术网_书友最值得收藏!

Scope of a variable and shadowing

All variables defined in the program bindings.rs have local scope delimited by the { } of the function which happens to be the main() function here, but this applies to any function. After the ending, }, they go out of scope and their memory allocation is freed.

We can even make a more limited scope inside a function by defining a code block as all code contained within a pair of curly braces { }, as in the following snippet:

// see Chapter 2/code/scope.rs 
fn main() { 
  let outer = 42; 
   { // start of code block 
        let inner = 3.14; 
        println!("block variable: {}", inner); 
        let outer = 99; // shadows the first outer variable 
        println!("block variable outer: {}", outer); 
    } // end of code block 
    println!("outer variable: {}", outer); 
} 

The preceding code gives the following output:

    block variable: 3.14
    block variable outer: 99
    outer variable: 42

A variable defined in the block (like inner) is only known inside that block. A variable in the block can also have the same name as a variable in an enclosing scope (like outer), which is replaced (shadowed) by the block variable until the block ends. What do you expect when you try to print out inner after the block? Try it out.

Why would you want to use a code block? In the section Expressions, we will see that a code block can return a value that can be bound to a variable with the let binding. A code block can also be empty as { }.

主站蜘蛛池模板: 福州市| 井研县| 洛南县| 德江县| 崇义县| 台中县| 延川县| 松溪县| 定日县| 札达县| 锡林浩特市| 潮安县| 来安县| 宁陕县| 彰化市| 宝坻区| 安福县| 神池县| 怀仁县| 库车县| 绥德县| 咸阳市| 长乐市| 阳东县| 甘孜| 五莲县| 平昌县| 汾阳市| 资溪县| 泸溪县| 隆子县| 泸西县| 昌都县| 山丹县| 托里县| 阜康市| 盐亭县| 社旗县| 东源县| 平陆县| 盱眙县|