- Rust Essentials(Second Edition)
- Ivo Balbaert
- 262字
- 2021-07-02 15:30:39
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 { }.
- R語言經典實例(原書第2版)
- Python量化投資指南:基礎、數據與實戰
- 軟件架構設計:大型網站技術架構與業務架構融合之道
- 自己動手實現Lua:虛擬機、編譯器和標準庫
- Unity 2020 Mobile Game Development
- WordPress Plugin Development Cookbook(Second Edition)
- Apache Kafka Quick Start Guide
- Unity 2D Game Development Cookbook
- 利用Python進行數據分析
- OpenGL Data Visualization Cookbook
- 基于ARM Cortex-M4F內核的MSP432 MCU開發實踐
- 編寫高質量代碼:改善Objective-C程序的61個建議
- Building Serverless Web Applications
- Advanced UFT 12 for Test Engineers Cookbook
- Python Projects for Kids