1

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 afaik 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.

Ken White
  • 123,280
  • 14
  • 225
  • 444
ajp
  • 1,723
  • 14
  • 22
  • I don't think so, I think the first code is how it's supposed to be. What's wrong with it? – Finomnis Jun 02 '23 at 18:32
  • I'd just like to reduce verbosity. The real code is destructuring a more complex struct, and there are multiple boilerplate variable-copying lines. – ajp Jun 02 '23 at 18:34
  • You could wrap all of those variables in a struct. You can assign multiple values in the same line. There are many improvements, but none of them are related to directly destructuring an enum into an outer variable. I don't think it's possible right now. – Finomnis Jun 02 '23 at 18:45
  • Related discussion: https://internals.rust-lang.org/t/pre-rfc-allow-existing-variables-in-destructuring-tuples/10970/5 It's not completely related, but a previous step. So if this isn't possible yet, I don't think performing it conditionally is or will be possible anytime soon. But again, I'm sure there are other ways to optimize the code, just not in the way you asked. – Finomnis Jun 02 '23 at 18:45
  • Related: you can destructure when assigning as shown here [Can I destructure a tuple without binding the result to a new variable in a let/match/for statement?](/a/71261230/2189130) but not in a `let`. – kmdreko Jun 02 '23 at 18:47
  • I'd be nice if `while Some(x) = foo(x)` worked, but currently it [crashes the compiler](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=9144a1f11298b91af386dc024b8679e1) ... Maybe in a future version something like this would be possible. For now you could always create a macro for it. – Filipe Rodrigues Jun 02 '23 at 22:47

1 Answers1

0

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.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116