A D vs. Rust example

Don Allen donaldcallen at gmail.com
Fri Oct 21 13:44:56 UTC 2022


On Friday, 21 October 2022 at 07:37:41 UTC, Stefan Hertenberger 
wrote:
> On Thursday, 20 October 2022 at 22:41:34 UTC, rassoc wrote:
>> On 20/10/2022 15:37, Don Allen via Digitalmars-d wrote:
>>> [...]
>>
>> 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);
>> }
>> ```
>
> You don't need to reorder, just use references
>
> ```rust
> fn main() {
>     let mut foo = 5;
>     let bar = |val: &mut i32| {
>         *val = 17;
>     };
>     let baz = |val: &mut i32| {
>         *val = 42;
>     };
>     bar(&mut foo);
>     println!("{}", &mut foo);
>     baz(&mut foo);
>     println!("{}", &mut foo);
>
> }
> ```

Which is contrary to the purpose of using closures -- to capture 
free variables in the lexical environment, rather than having to 
pass them as arguments. What you have done above could (and 
should) be re-written with ordinary functions.


More information about the Digitalmars-d mailing list