A D vs. Rust example
Stefan Hertenberger
SHertenberger at Web.de
Fri Oct 21 07:37:41 UTC 2022
On Thursday, 20 October 2022 at 22:41:34 UTC, rassoc wrote:
> 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);
> }
> ```
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);
}
```
More information about the Digitalmars-d
mailing list