Salta al contenuto

Piero Bosio Social Web Site Personale Logo Fediverso

Social Forum federato con il resto del mondo. Non contano le istanze, contano le persone

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

Senza categoria
2 2 0
  • An amusing but also actually useful thing in : 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 : 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
    };
    ```

  • Oblomovundefined Oblomov ha condiviso questa discussione

Gli ultimi otto messaggi ricevuti dalla Federazione
Post suggeriti