且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

let-rebinding 和标准分配有什么区别?

更新时间:2023-08-23 13:38:40

第二个 let x 引入了第二个绑定,该绑定隐藏块其余部分的第一个绑定.也就是说,有两个名为 x 的变量,但是您只能在 let x = 12; 语句之后的块语句中访问第二个变量.这两个变量不需要具有相同的类型!

The second let x introduces a second binding that shadows the first one for the rest of the block. That is, there are two variables named x, but you can only access the second one within the block statement after the let x = 12; statement. These two variables don't need to have the same type!

然后,在块语句之后,第二个 x 超出范围,因此您再次访问第一个 x.

Then, after the block statement, the second x is out of scope, so you access the first x again.

然而,如果你改写 x = 12;,那就是一个赋值表达式:x 中的值被覆盖.这不会引入新的变量,因此被赋值的类型必须与变量的类型兼容.

However, if you write x = 12; instead, that's an assignment expression: the value in x is overwritten. This doesn't introduce a new variable, so the type of the value being assigned must be compatible with the variable's type.

如果你写一个循环,这个区别很重要.例如,考虑这个函数:

This difference is important if you write a loop. For example, consider this function:

fn fibonacci(mut n: u32) -> u64 {
    if n == 0 {
        return 1;
    }

    let mut a = 1;
    let mut b = 1;

    loop {
        if n == 1 {
            return b;
        }

        let next = a + b;
        a = b;
        b = next;
        n -= 1;
    }
}

此函数重新分配变量,以便循环的每次迭代都可以对前一次迭代分配的值进行操作.

This function reassigns variables, so that each iteration of the loop can operate on the values assigned on the preceding iteration.

但是,您可能会想像这样编写循环:

However, you might be tempted to write the loop like this:

loop {
    if n == 1 {
        return b;
    }

    let (a, b) = (b, a + b);
    n -= 1;
}

这不起作用,因为 let 语句引入了新变量,这些变量将在下一次迭代开始之前超出范围.在下一次迭代中,(b, a + b) 仍将使用原始值.

This doesn't work, because the let statement introduces new variables, and these variables will go out of scope before the next iteration begins. On the next iteration, (b, a + b) will still use the original values.