变量绑定与解构

186 阅读2分钟

变量可变性

  • Rust 允许手动设置变量的可变性,提供了灵活性和安全性。
  • 变量默认是不可变的,使用 mut 关键字可以使其变为可变。

变量命名

  • 遵循 Rust 命名规范,关键字不能用作变量或函数名称。

变量绑定

  • 使用 let 进行变量绑定,如:let a = "hello world";

变量可变性示例

fn main() {
    let x = 5;
    println!("The value of x is: {}", x);
    // 下面的代码将导致编译错误,因为 x 是不可变的
    x = 6;
    println!("The value of x is: {}", x);
}

编译错误提示:

error[E0384]: cannot assign twice to immutable variable `x`

可变变量示例

fn main() {
    let mut x = 5;
    println!("The value of x is: {}", x);
    x = 6; // 可以修改 x 的值
    println!("The value of x is: {}", x);
}

运行结果:

The value of x is: 5
The value of x is: 6

使用下划线忽略未使用的变量

fn main() {
    let _x = 5; // 忽略未使用的变量
    let y = 10; // 未使用的变量 y 将产生警告
}

编译警告:

warning: unused variable: `y`

变量解构

fn main() {
    let (a, mut b): (bool, bool) = (true, false);
    println!("a = {:?}, b = {:?}", a, b);
    b = true;
    assert_eq!(a, b);
}

解构式赋值

struct Struct {
    e: i32,
}

fn main() {
    let (a, b, c, d, e);
    (a, b) = (1, 2);
    [c, .., d, _] = [1, 2, 3, 4, 5];
    Struct { e, .. } = Struct { e: 5 };

    assert_eq!([1, 2, 1, 4, 5], [a, b, c, d, e]);
}

变量和常量之间的差异

  • 常量使用 const 关键字声明,类型必须标注,如:const MAX_POINTS: u32 = 100_000;
  • 常量在编译后确定值,不可变。

变量遮蔽(shadowing)

复制
fn main() {
    let x = 5;
    let x = x + 1; // x 被遮蔽,新值为 6
    {
        let x = x * 2; // x 再次被遮蔽,新值为 12
        println!("The value of x in the inner scope is: {}", x);
    }
    println!("The value of x is: {}", x); // 输出 6
}

运行结果:

The value of x in the inner scope is: 12
The value of x is: 6