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,我们可以对一个值进行一些转换,但在这些转换完成后,变量将是不可变的。

相关推荐
析数塔15 小时前
编译两分钟,修改五秒钟:Zig构建系统重构解决的老问题
程序员·rust
Kapaseker17 小时前
Rust 是如何干掉空指针的
rust·kotlin
特立独行的猫a17 小时前
OHOS (OpenHarmony) 鸿蒙的Rust 交叉编译环境搭建指南
华为·rust·harmonyos·鸿蒙pc
Rust研习社17 小时前
从 LaunchBadge 到 transact-rs:SQLx 社区迈出可持续治理的第一步
开发语言·后端·rust
techdashen2 天前
你想在 Rust 中实现动态库热重载?
开发语言·chrome·rust
只会写bug的靓仔2 天前
我把 Electron+Go 的 LOL 战绩工具重写成 Tauri+Rust,安装包从 128 MB 砍到 5 MB
golang·rust·electron
本地化文档2 天前
sphinxcontrib-rust-docs-l10n
python·rust·github·gitcode·sphinx
韦胖漫谈IT2 天前
选语言不是站队,是选适合问题的工具
java·python·ai·rust·go·技术落地
特立独行的猫a2 天前
鸿蒙 PC 平台 Rust 语言第三方库与应用移植全景指南
华为·rust·harmonyos·三方库·鸿蒙pc
红尘散仙2 天前
我把终端小说阅读器接上了 AI Agent:TRNovel 现在能用 skill 生成书源了
人工智能·后端·rust