rust遮蔽(shadow)示例代码

rust 复制代码
fn main() {
    let x = 5;

    let x = x + 1;
    {
        let x = x * 2;
        println!("The value of x in the inner scope is: {}", x);
    }
	//x=10; //这样写会编译报错
    println!("The value of x is: {}", x);
}

这个程序首先将数值 5 绑定到 x。然后通过重复使用 let x = 来遮蔽之前的 x,并取原来的值加上 1,所以 x 的值变成了 6。在内部作用域内,第三个 let 语句同样遮蔽前面的 x,取之前的值并乘上 2,得到的 x 值为 12。当该作用域结束时,内部遮蔽结束并且 x 恢复成 6。当运行此程序,将输出以下内容:

bash 复制代码
$ cargo run
   Compiling variables v0.1.0 (file:///projects/variables)
    Finished dev [unoptimized + debuginfo] target(s) in 0.31s
     Running `target/debug/variables`
The value of x in the inner scope is: 12
The value of x is: 6

遮蔽和将变量标记为 mut 的方式不同,因为除非我们再次使用 let 关键字,否则若是我们不小心尝试重新赋值给这个变量,我们将得到一个编译错误。通过使用 let,我们可以对一个值进行一些转换,但在这些转换完成后,变量将是不可变的。

相关推荐
techdashen12 小时前
每次 `cargo build` 背后,有人在默默撑着这一切
rust
Binarydog_Lee12 小时前
Rust 核心机制:所有权、借用与生命周期
开发语言·rust
卜夋14 小时前
Rust 学习笔记 - Day 6: 引用与借用
后端·rust
zandy101116 小时前
衡石科技|HENGSHI CLI登场,以Rust架构驱动BI自动驾驶
开发语言·科技·rust
沛沛rh4516 小时前
用 Rust 实现用户态调试器:mini-debugger项目原理剖析与工程复盘
开发语言·c++·后端·架构·rust·系统架构
BugShare18 小时前
一个用 Rust 编写的、速度极快的 Python 包和项目管理器
开发语言·python·rust
Binarydog_Lee19 小时前
Rust 生命周期机制详解:彻底理解 ‘static
rust
techdashen19 小时前
Rust 正式成立 Types Team:类型系统终于有了专属团队
开发语言·后端·rust