简体   繁体   English

Rust let 绑定的不变性

[英]immutability of rust let bindings

I thought that let is supposed to be an immutable binding.我认为let应该是一个不可变的绑定。 Why does the correct code work then?为什么正确的代码会起作用? (assigned a twice) (分配a两次)

let a = [1, 2, 3, 4, 5];
println! ("{:?}", a);

let (a, b, c) = (1,2,3);
println! ("{:?}", a);
println! ("{:?}", b);
println! ("{:?}", c);

And the result of cargo run is:货物运行的结果是:

Guess the number! From a 1 - 100 inclusive
[1, 2, 3, 4, 5]
1
2
3

Your code is more or less equivalent to this:您的代码或多或少与此等效:

let first_a = [1, 2, 3, 4, 5];
println! ("{:?}", first_a);

let (second_a, b, c) = (1,2,3);
println! ("{:?}", second_a);
println! ("{:?}", b);
println! ("{:?}", c);

The second a is a completely new variable.第二个a是一个全新的变量。 The first a is no longer accessible once you create a second one.创建第二个 a 后,第一个a将不再可访问。

a is being shadowed . a遮蔽

let a = 5;
a = 6; // not allowed

let a = 5;
let a = 6; //allowed

Bad form to do this in the same block like that.在同一个块中执行此操作的错误形式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM