可变性

变量绑定默认是不可变的,但是可以使用 mut 修饰符来覆盖。

fn main() {
    let _immutable_binding = 1;
    let mut mutable_binding = 1;

    println!("Before mutation: {}", mutable_binding);

    // Ok
    mutable_binding += 1;

    println!("After mutation: {}", mutable_binding);

    // Error! Cannot assign a new value to an immutable variable
    _immutable_binding += 1;
}

编译器会对可变性错误抛出详细的诊断信息。