An amusing but also actually useful thing in #RustLang: I realised this week that in some situations there's a good reason to write an apparent no-op let statement.let x = x;Because if x was previously mut, this makes it not mut any more
-
An amusing but also actually useful thing in #RustLang: I realised this week that in some situations there's a good reason to write an apparent no-op let statement.
let x = x;
Because if x was previously mut, this makes it not mut any more.
In particular, this is a useful precaution for algorithms that use a data structure like a collection in two phases: (1) populate the data structure, (2) read stuff back out of it. If a stray mutation of the DS were to appear in phase 2 then perhaps it would invalidate all the stuff you'd already read out. Making the DS immutable at the end of phase 1 means the compiler will complain instead of letting the bug get as far as run time.
Perhaps this is a well-known technique already? But I worked it out for myself, by thinking "it would be nice to be able to remove 'mut' from this variable here … hmm, I feel as if just 'let x=x' ought to have that effect … yes it does, aha!"
-
An amusing but also actually useful thing in #RustLang: I realised this week that in some situations there's a good reason to write an apparent no-op let statement.
let x = x;
Because if x was previously mut, this makes it not mut any more.
In particular, this is a useful precaution for algorithms that use a data structure like a collection in two phases: (1) populate the data structure, (2) read stuff back out of it. If a stray mutation of the DS were to appear in phase 2 then perhaps it would invalidate all the stuff you'd already read out. Making the DS immutable at the end of phase 1 means the compiler will complain instead of letting the bug get as far as run time.
Perhaps this is a well-known technique already? But I worked it out for myself, by thinking "it would be nice to be able to remove 'mut' from this variable here … hmm, I feel as if just 'let x=x' ought to have that effect … yes it does, aha!"
@simontatham It's a thing, though I usually prefer encasing the mutability part in a block:
```
let x = {
let mut x = ...;
x += ...;
x
};
``` -
undefined Oblomov ha condiviso questa discussione