A D vs. Rust example
victoroak
jackpboy at gmail.com
Sat Oct 22 05:35:22 UTC 2022
On Thursday, 20 October 2022 at 13:37:07 UTC, Don Allen wrote:
>
> ````
> fn main() {
> let mut foo = 5;
> let mut bar = || {
> foo = 17;
> };
> let mut baz = || {
> foo = 42;
> };
> bar();
> println!("{}", &mut foo);
> baz();
> println!("{}", &mut foo);
>
> }
> ````
>
I think the way it would be advised to write it in Rust would be
something like this instead of using RefCell:
```
fn main() {
struct State {
foo: i32
}
impl State {
fn bar(&mut self) {
self.foo = 17;
}
fn baz(&mut self) {
self.foo = 42;
}
}
let mut state = State {
foo: 0
};
state.bar();
println!("{}", state.foo);
state.baz();
println!("{}", state.foo);
}
```
The problem is that both closures have a mutable reference to the
same value and this is not allowed in Rust, you could solve this
making the functions get a mutable reference to the variable but
using a struct in this case is better IMO.
More information about the Digitalmars-d
mailing list