Suppose I have this code.
fn main() {
let mut x = 123;
let mut y = 456;
let mut z = 789;
x += y; y *= z; z %= x; // random operations
x = 1;
x += y; y *= z; z %= x;
z = z & y;
x += y; y *= z; z %= x;
println!("{} {} {}", x, y, z);
}
Totally contrived, but hopefully the idea is clear. I have these local variables that I manipulate in a certain complex way more than once.
Obviously, I would like to avoid duplication and reorganize this manipulation. At the same time, there are so many variables that I would prefer not to pass them as mutable reference arguments to an external utility.
If it were, say, C ++, I could hide the variables in the global scope and define another function, or use lambda capture in later versions. I tried to do the appropriate thing in Rust with closure:
fn main() {
let mut x = 123;
let mut y = 456;
let mut z = 789;
let f = || {
x += y; y *= z; z %= x; // random operations
};
f();
x = 1;
f();
z = z & y;
f();
println!("{} {} {}", x, y, z);
}
, Rust , x, y, z f. , f , x, y, z main. Rust , f - , , , , , " " , .
?
, , , println!, f , , , f.