第一章 不可变的变量

  • 不可变的变量

Rust编程语言和其他的编程语言不同,它的变量初始化之后默认是不可以改变它的赋值的。这是Rust编程语言独有的特性。

rust 复制代码
fn main() {

    let x = 5;

    println!("x的值是: {}", x);

    x = 6;

    println!("x的值是: {}", x);

}

如果运行上面的代码,系统会提示如下的错误信息:

bash 复制代码
error[E0384]: cannot assign twice to immutable variable `x`

 --> src\main.rs:4:5

  |

2 |     let x = 5;

  |         - first assignment to `x`

3 |     println!("x的值是: {}", x);

4 |     x = 6;

  |     ^^^^^ cannot assign twice to immutable variable

  |

help: consider making this binding mutable

  |

2 |     let mut x = 5;

  |         +++


For more information about this error, try `rustc --explain E0384`.

error: could not compile `lession_01_01` (bin "lession_01_01") due to 1 previous error

上面的信息告诉我们对不可变的变量x进行了两次赋值,如果需要更改x的值,需要使用mut修饰符来对x变量进行修改。即:let mut x = 5;

通过上面的代码运行,我们可以获知下面一些信息:

  1. 变量的定义语法:let 变量名称:变量类型 = 变量初始化值
  2. 变量默认是不可修改的。
  3. 如果变量需要更改为可变的,需要再变量名称前面增加修饰符"mut"。即:let mut 变量名称:变量类型 = 变量初始化值

修改上面的代码,使变量x更改为可以修改的变量。

rust 复制代码
fn main() {

    let mut x = 5;

    println!("x的值是: {}", x);

    x = 6;

    println!("x的值是: {}", x);

}

执行 cargo run 运行上面的代码,系统给出下面的结果:

bash 复制代码
   Compiling lession_01_02 v0.1.0 (D:\projects\rust\rust_learn\lession_01_02)

    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.70s

     Running `target\debug\lession_01_02.exe`

x的值是: 5

x的值是: 6

系统没有报错,并给出了正确的响应。

相关推荐
马优晨8 小时前
Freemarker 完整讲解(后端 Java 模板引擎)
java·开发语言·freemarker·freemarker 完整讲解·freemarker模板引擎
weixin_446260859 小时前
HACO:面向动态部署环境的对冲式智能计算可靠多智能体调度框架
后端·python·flask
doiito10 小时前
【AI 应用】从“外国人味”到地道中文:kokoroi-rs v0.1.2 架构升级深度解析
ai·rust·系统设计
人邮异步社区10 小时前
怎么把C语言学到精通?
c语言·开发语言
心平气和量大福大10 小时前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf
ttwuai11 小时前
Cursor 生成 CRUD 后,Go 后台接口别只测 200:JWT、RBAC 和 tenant_id 怎么验
开发语言·后端·golang
用户83562907805111 小时前
Python 实现 Excel 页面布局与打印设置自动化
后端·python
用户99314415798411 小时前
微服务框架中获取用户信息
后端
এ慕ོ冬℘゜11 小时前
前端基础:什么是时间戳?JS获取时间戳三种方法与实战用途
开发语言·前端·javascript