可变性
- 声明变量使用
let
关键字
- 默认情况下,变量是不可变的(Immutable)
- 声明变量时,在变量前面加上
mut
,就可以使变量可变
1 2 3 4 5
| fn main() { let mut foo = 1; foo = 2; println!("bar is {}", foo) }
|
变量与常量
常量(constant)在绑定值以后也是不可变的,但是它与不可变的变量有很多区别:
- 不可以使用 mut,常量永远都是不可变的
- 声明常量使用
const
关键字,它的类型必须被标注
- 常量可以在任何作用域内进行声明,包括全局作用域
- 常量只可以绑定到常量表达式,无法绑定到函数的调用结果或只能在运行时才能计算出的值
在程序运行期间,常量在其声明的作用域内一直有效
命名规范:Rust 里常量使用全大写字母,每个单词之间用下划线分开,例如:MAX_POINTS
1 2
| const MAX_POINTS: u32 = 100_1000;
|
Shadow(隐藏)
Rust 中允许使用同名的变量来覆盖之前的变量,区别于 Golang,不仅可以用于覆盖值,可以类型也可以不一样。一般用于在不额外声明变量的场景下,进行类型转换。
1 2 3 4 5
| fn main() { let x = 5; let x = x + 1; println!("x is {}", x) }
|
使用 mut 关键字
1 2 3 4 5
| fn main() { let mut x = 5; x = x + 1; println!("x is {}", x) }
|
shadow 和把变量标记为 mut 是不一样的
- 如果不使用 let 关键字,那么重新给非 mut 的变量赋值会导致编译时错误
- 使用 let 声明的同名新变量,也是不可变的
- 使用 let 声明的同名新变量,它的类型可以与之前不同
1 2 3 4 5 6
| fn main() { let name = "Arthur Morgan"; let name = name.len();
println!("{}", name) }
|
使用 mut 关键字
1 2 3 4 5 6
| fn main() { let mut name = "Arthur Morgan"; name = name.len();
println!("{}", name) }
|
1 2 3 4 5 6
| $ cargo run error[E0308]: mismatched types --> src/main.rs:3:12 | 3 | name = name.len(); | ^^^^^^^^^^ expected `&str`, found `usize`
|