Rust 变量与可变性

不可变变量

在 Rust 中变量默认是不可变的
使用 let 定义 x = 5, 然后将 6 赋值给 x,这样是不能通过编译的。

src/main.rs

fn main() {
    let x = 5;
    x = 6;
}

执行 rustc main.rs 会得到如下错误:

error[E0384]: cannot assign twice to immutable variable `x`
 --> main.rs:3:5
  |
2 |     let x = 5;
  |         -
  |         |
  |         first assignment to `x`
  |         help: make this binding mutable: `mut x`
3 |     x = 6;
  |     ^^^^^ cannot assign twice to immutable variable

error: aborting due to previous error

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

遮蔽 (shadowing)

可以再次使用 let 遮蔽同名变量

src/main.rs

fn main() {
    let x = 5;
    let x = 6;
    let x = "";
}

可变变量

要声明可变变量则需要使用 mut 关键字

fn main() {
    let mut x = 5;
    x = 6;
}

常量

使用 const 关键字可以声明常量

fn main() {
    const MAX_POINTS: u32 = 100_000;
}

不可变变量和常量的区别如下:

  • 常量必须指定类型
  • 常量不能和 mut 关键字一起使用
  • 常量不能被遮蔽
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容