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

相关推荐
青川Lapis6 小时前
RUST:错误处理 thiserror 详解
rust
Source.Liu11 小时前
【A11】拥有者模式平台架构笔记
windows·笔记·架构·rust
sayang_shao12 小时前
用 Rust 开发 STM32H743:从零搭建一个能烧录、能看日志的项目
stm32·单片机·rust
qq_4069810312 小时前
大白话rust系列02原始数据类型
rust
遇码14 小时前
macOS 触摸板捏合在 GPUI 里无响应:vendor 打补丁,把手势合成为 cmd+滚轮事件
rust·图形渲染·策略模式·桌面应用·gpui
geovindu15 小时前
rust: Chain of Responsibility Pattern
开发语言·后端·设计模式·rust·责任链模式·行为模式
geovindu16 小时前
rust: Chain of Responsibility Pattern (续)
开发语言·后端·设计模式·rust·责任链模式·行为模式
Amos_Web17 小时前
Rspack 源码解析(二十四):AssetPlugin 如何让图片同时是「URL 字符串」和「真实文件」
前端·rust·前端框架
wflynn2 天前
GitHub 今日推荐|solidcraft:Rust 跨平台参数化 CAD,支持 AI 代理通过 MCP 协议驱动建模
rust·开源·github·cad·3d-modeling·brep