Rust 中的不可变数据绑定

Beginner

This tutorial is from open-source community. Access the source code

简介

在本实验中,冻结的概念被解释为数据通过相同名称不可变地绑定的状态,这使得数据在不可变绑定超出作用域之前无法被修改。

注意:如果实验未指定文件名,你可以使用任何你想要的文件名。例如,你可以使用 main.rs,并通过 rustc main.rs &&./main 进行编译和运行。

冻结

当数据通过相同名称被不可变地绑定时,它也会被“冻结”。在不可变绑定超出作用域之前,“冻结”的数据无法被修改:

fn main() {
    let mut _mutable_integer = 7i32;

    {
        // 由不可变的 `_mutable_integer` 进行遮蔽
        let _mutable_integer = _mutable_integer;

        // 错误!`_mutable_integer` 在这个作用域中被冻结
        _mutable_integer = 50;
        // FIXME ^ 注释掉这一行

        // `_mutable_integer` 超出作用域
    }

    // 可以!`_mutable_integer` 在这个作用域中没有被冻结
    _mutable_integer = 3;
}

总结

恭喜你!你已经完成了“冻结”实验。你可以在 LabEx 中练习更多实验来提升你的技能。