在 Rust 中多次使用具有相同变量名的 let 关键字

Using let keyword multiple times with same variable name in rust

Rust 新手,我已经度过了卡在借用检查器的阶段,但我仍然不明白为什么这段代码可以工作或通过。我正在实现一个类似结构的枚举,它充当某种形式的节点,可以附加到:

#[derive(Debug)]
enum Node {
    Val {num:u32, next:Box<Node>},
    Nil
}

impl Node {
    fn put_next(&self, i:u32) -> Node {
       match self {
           Node::Val {num, next:_} => Node::Val {num:*num, next:Box::new(Node::Val {num:i, next:Box::new(Node::Nil)})},
           Node::Nil => Node::Val {num:i, next:Box::new(Node::Nil)}
       }
    }
}

以下 main 函数由于显而易见的原因不起作用,您不能分配给不可变变量:

fn main() {
   let foo = Node::Val {num:5, next:Box::new(Node::Nil)};
   foo = foo.put_next(30);
   println!("foo {:?} ", foo);
}

但是,如果我再次将 let 与 foo 一起使用,代码可以正常运行!

fn main() {
   let foo = Node::Val {num:5, next:Box::new(Node::Nil)};
   let foo = foo.put_next(30);
   println!("foo {:?} ", foo);
}
// foo Val { num: 5, next: Val { num: 30, next: Nil } } 

我的问题是,为什么编译器允许 let 被同一个变量多次使用?如果是故意的,那甚至意味着什么或表明什么?是不是在幕后创建了一个名为 foo 的新变量并删除了旧变量?

这称为变量阴影。第二个 foo 没有绑定到与第一个相同的值,而是一个全新的值。有关详细信息,请查看 Shadowing chapter of The Rust Book,即:

[...] you can declare a new variable with the same name as a previous variable, and the new variable shadows the previous variable. Rustaceans say that the first variable is shadowed by the second, which means that the second variable’s value is what appears when the variable is used.