Rust学习笔记——基础篇2:变量与常量

变量和常量

变量

Rust的变量会自动判断类型(也可以手动指定),且不能更改,是强类型语言

不可变变量

let 变量名 = 值;
let 变量名:数据类型 = 值;

变量声明后不可更改,但可以“重新绑定”为其他值(Rust里叫做重影),并且可以绑定为不同的数据类型

fn main() {
    let a = 1;
    a = 2;
}

运行结果:
error[E0384]: cannot assign twice to immutable variable `a`
 --> src/main.rs:3:5
  |
2 |     let a = 1;
  |         -
  |         |
  |         first assignment to `a`
  |         help: consider making this binding mutable: `mut a`
3 |     a = 2;
  |     ^^^^^ cannot assign twice to immutable variable

  -----------------------------------------------------------------------------

fn main() {
    let a = 1;
    let a = "hello";

    println!("{a}");
}

运行结果:
hello

可变变量

let mut 变量名 = 值;

常量

可以用以下方式声明一个常量

const 常量名:数据类型 = 值;

注意:常量必须手动指定数据类型,且常量可以在任意范围(包括全局)声明,以下程序是合法的

const a:u32 = 1;

fn main() {
    const b:i32 = 2;
}

常量与不可变变量的区别在于不可变变量可以重新绑定,而常量不行

fn main() {
    const a:usize = 1;
    let a = 2;
}

运行结果:
error[E0005]: refutable pattern in local binding
 --> src/main.rs:3:9
  |
2 |     const a:usize = 1;
  |     ------------- constant defined here
3 |     let a = 2;
  |         ^
  |         |
  |         pattern `_` not covered
  |         missing patterns are not covered because `a` is interpreted as a constant pattern, not a new variable
  |         help: introduce a variable instead: `a_var`
  |
  = note: the matched value is of type `usize`
posted @ 2023-05-28 15:53  浮生偷闲zjy  阅读(17)  评论(0编辑  收藏  举报