rust里mut 和遮蔽之间的区别

mut遮蔽之间的一个区别是,因为我们在再次使用 let 关键字时有效地创建了一个新的变量,所以我们可以改变值的类型,但重复使用相同的名称。例如,假设我们程序要求用户输入空格字符来显示他们想要的空格数目,但我们实际上想要将该输入存储为一个数字:

rust 复制代码
let spaces = "   ";
let spaces = spaces.len();

第一个 spaces 变量是一个字符串类型,第二个 spaces 变量是一个数字类型。所以变量遮蔽可以让我们不必给出不同的名称,如 spaces_str 和 spaces_num,相反我们可以重复使用更简单的 spaces 变量名。然而,如果我们对此尝试使用 mut,如下所示,我们将得到一个编译期错误:

rust 复制代码
//This code does not compile!
let mut spaces = "   ";
spaces = spaces.len();

该错误表明我们不允许更改变量的类型:

bash 复制代码
$ cargo run
   Compiling variables v0.1.0 (file:///projects/variables)
error[E0308]: mismatched types
 --> src/main.rs:3:14
  |
2 |     let mut spaces = "   ";
  |                      ----- expected due to this value
3 |     spaces = spaces.len();
  |              ^^^^^^^^^^^^ expected `&str`, found `usize`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `variables` due to previous error
相关推荐
思麟呀14 分钟前
C++11并发编程:call_once一次性执行+atomic原子类型+CAS无锁编程+自旋锁
linux·开发语言·jvm·c++·windows
码不停蹄的玄黓38 分钟前
Java 生产者-消费者模型详解
java·开发语言·python
爱讲故事的41 分钟前
操作系统第一讲复习:为什么学习操作系统,以及操作系统到底在做什么?
linux·开发语言·windows·学习·ubuntu·c#
笨蛋不要掉眼泪1 小时前
Java并发编程:Executors框架类深度解析
java·开发语言·并发
_童年的回忆_2 小时前
【php】在linux下PHP安装amqp扩展
linux·开发语言·php
AIMath~2 小时前
python中的uv命令揭秘
开发语言·python·uv
弹简特2 小时前
【零基础学Python】06-Python模块和包、异常处理、文件常用操作
开发语言·python
x***r1512 小时前
Postman-win64-7.2.2-Setup安装步骤详解(附API接口测试与参数配置教程)
开发语言·lua
念恒123062 小时前
Python 面向对象编程核心:对象、实例化、封装与变量作用域
开发语言·python
大菜菜小个子2 小时前
template<typename T>使用
java·开发语言·算法