知识卡片
遮蔽创建新的绑定
同名的第二次 let 给名字建立新的绑定,可以改变类型。示例 let spaces = spaces.len() 以旧字符串计算长度,后续 spaces 则指向整数。内层块声明的同名绑定在块外不可见。可变赋值仍操作原来的绑定,类型须兼容。
这张卡片看不懂?
这张卡片已通过人工审查,不再接受失败反馈。
已有反馈 · 0 条
还没有人提交反馈。
在整书笔记中的位置
原书出处 · 1 处
- 常见编程概念 Variables and Mutability · 查看原书依据
The other difference between mut and shadowing is that because we’re effectively creating a new variable when we use the let keyword again, we can change the type of the value but reuse the same name. For example, say our program asks a user to show how many spaces they want between some text by inputting space characters, and then we want to store that input as a number:
参考来源
- 位置:《The Rust Programming Language(第2版)》第03章 常见编程概念(来源项目 a19c7933-4eda-4176-aebd-30fe7e1ad292,`extracted/The Rust Programming Language(第2版)/_epub-src/c03.xhtml`,块 0042)
- 结论依据:原文解释重新 let 可以改变类型,并对比 mut 的类型约束。
- 原始内容:The other difference between mut and shadowing is that because we’re effectively creating a new variable when we use the let keyword again, we can change the type of the value but reuse the same name. For example, say our program asks a user to show how many spaces they want between some text by inputting space characters, and then we want to store that input as a number: