开发环境
- Windows 10
- Rust 1.51
- VS Code

项目工程
这里继续沿用上次工程rust-demo。

目标
本次项目主要介绍Rust语言的变量,不需要额外添加依赖库。
变量声明
先看下面的代码
fn main() {
let x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
}
编译&运行
cargo run
会出现编译错误,具体如下:

使用下述命令查看详细信息
rustc --explain E0384
可见下述详细信息

根据上述解决方案,需要添加关键字mut,那么修改后的代码如下:
fn main() {
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
}
编译&运行
cargo run
运行结果

本章重点
- 和其它语言不同,变量通过关键字let声明。
- 变量想多次赋值或使用,需要声明为mut变量。
2674

被折叠的 条评论
为什么被折叠?



