Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a let binding assign to a mutable variable rather than shadowing?

I have some code that looks like this:

let mut x = ...;
while let Some(x_) = foo(x) {
    x = x_;
    bar(x);
}
baz(x);

I'd like to write it as:

let mut x = ...;
while let Some(x) = foo(x) {
    bar(x);
}
baz(x);

but as far as I know this will shadow the outer mutable x instead of assigning to it. Note that I need access to the final value of x after the loop ends.

like image 474
ajp Avatar asked Jan 23 '26 12:01

ajp


1 Answers

No, let always binds a new variable, even when inside of if or while. The only way to reassign the value of an existing variable is with the infix = operator.

like image 84
Silvio Mayolo Avatar answered Jan 26 '26 09:01

Silvio Mayolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!