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@sociale.network shared this topic on
Gli ultimi otto messaggi ricevuti dalla Federazione
Post suggeriti
-
-
Rust sempre più presente nel Kernel Linux 6.18La nuova versione accoglie una valanga di codice Rust, portando miglioramenti al core, al driver core (con supporto DebugFS/IRQ) e supporto iniziale per le variabili atomiche LKMM.
Uncategorized
1
-
-
Sorry, I don't do rust, but I still thought this was hilarious!#rustlang #Tylenol #Programming
Uncategorized
1