一 创建项目
cargo new variables
二 变量可变性的实例错误代码
vim ./src/main.rs
fn main() {
let x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
}
三 编译查看错误提示
cargo run
cargo run
Compiling variables v0.1.0 (/home/li/projects/variables)
error[E0384]: cannot assign twice to immutable variable `x`
--> src/main.rs:4:5
|
2 | let x = 5;
| -
| |
| first assignment to `x`
| help: make this binding mutable: `mut x`
3 | println!("The value of x is: {}", x);
4 | x = 6;
| ^^^^^ cannot assign twice to immutable variable
error: aborting due to previous error
小结:默认情况,let定义的变量是不可变的,如果可变需加关键字mut
四 增加mut关键字,让变量可变
vim ./src/main.rs
fn main() {
let mut x = 5;
println!("The value of x is: {}", x);
x = 6;
println!("The value of x is: {}", x);
}
输出
cargo run
Compiling variables v0.1.0 (/home/li/projects/variables)
Finished dev [unoptimized + debuginfo] target(s) in 4.98s
Running `target/debug/variables`
The value of x is: 5
The value of x is: 6
五 常量
使用const关键字定义常量
const MAX_POINTS: u32 = 100_000; //在数字字面值下面插入下划线来提高数字可读性,这里等价于 100000
六 隐藏(shadowing)变量
重复使用let关键字,定义同名变量来隐藏之前的变量。
实际上是创建一个新的变量。
可改变变量的类型和值
fn main() {
let x = 5;
println!("The value of x is: {}", x);
let x = "6+1";
println!("The value of x is: {}", x);
}
如果使用mut,则会报编译错误
因为mut不允许改变变量类型
fn main() {
let mut x = 5;
println!("The value of x is: {}", x);
x = "6+1";
println!("The value of x is: {}", x);
}
cargo run
Compiling variables v0.1.0 (/home/li/projects/variables)
error[E0308]: mismatched types
--> src/main.rs:4:9
|
4 | x = "6+1";
| ^^^^^ expected integer, found reference
|
= note: expected type `{integer}`
found type `&'static str`
七总结
1 使用大型数据结构时,适当地使用可变变量
2 对于较小的数据结构,总是创建新实例
3 了解let,mut,const关键字用法