How to reorganize multiple manipulations with local variables?

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.

+4
2

- :

macro_rules! f {
    ($x:ident, $y:ident, $z:ident) => {{
        $x += $y;
        $y *= $z;
        $z %= $x;
    }}
}

f!(x, y, z). , , &mut int.

, x, y z , , x, y z (, - ).

macro_rules! f {
    () => {{
        x += y;
        y *= z;
        z %= x;
    }}
}

:

#![feature(macro_rules)]

fn main() {
    let mut x = 123i;
    let mut y = 456i;
    let mut z = 789i;

    macro_rules! f {
        () => {{
            x += y;
            y *= z;
            z %= x;
        }}
    }

    f!()
    x = 1;
    f!()
    z = z & y;
    f!()
    println!("{} {} {}", x, y, z);
}

: http://is.gd/sCaYMS

+4

Cell. . , , , . , .

use std::cell::Cell;

fn main() {
    let x = Cell::new(123i);
    let y = Cell::new(456i);
    let z = Cell::new(789i);

    let f = || {
        x.set(x.get() + y.get());
        y.set(y.get() * z.get());
        z.set(z.get() % x.get());
    };

    f();
    x.set(1);
    f();
    z.set(z.get() & x.get());
    f();
    println!("{} {} {}", x, y, z);
}

, , struct.

#[deriving(Show)]
struct Data {
    x: int,
    y: int,
    z: int
}

impl Data {
    fn f(&mut self) {
        self.x += self.y; 
        self.y *= self.z;
        self.z %= self.x;
    }
}


fn main() {
    let mut data = Data { x: 123, y: 456, z: 789 };

    data.f();
    data.x = 1;
    data.f();
    data.z = data.z & data.x;
    data.f();
    println!("{}", data);
}
+4

Source: https://habr.com/ru/post/1546795/


All Articles