A D vs. Rust example

rassoc rassoc at posteo.de
Thu Oct 20 22:41:34 UTC 2022


On 20/10/2022 15:37, Don Allen via Digitalmars-d wrote:
> Rust has closures. Great. So here's an example of an attempt to do something along the lines described above with a single mutable variable:
> 
> ````
> fn main() {
>      let mut foo = 5;
>      let mut bar = || {
>          foo = 17;
>      };
>      let mut baz = || {
>          foo = 42;
>      };
>      bar();
>      println!("{}", &mut foo);
>      baz();
>      println!("{}", &mut foo);
> 
> }
> ````

To be honest, these kind of access patterns are smelly and there almost always exists a more elegant alternative.

Regarding that example code above, the burrow checker will be happy if you reorder it slightly:

```rust
fn main() {
     let mut foo = 5;
     let mut bar = || {
         foo = 17;
     };
     bar();
     println!("{}", &mut foo);
     
     // just moved this down here
     let mut baz = || {
         foo = 42;
     };
     baz();
     println!("{}", &mut foo);
}
```


More information about the Digitalmars-d mailing list