2

I have a few methods in Rust that return two elements, and it really makes sense for me in those scenarios to return two elements. Though, when actually calling those methods I noticed that Rust does not allow using tuples as lvalue, so I cannot reassign to them. Assuming test() is a method that returns two values, I end up writing a lot of code that looks like this:

let (mut val1, mut val2) = test();

for i in 0..100 {
   // partially removed for brevity;
   let (_val1, _val2) = test();
   val1 = _val1;
   val2 = _val2;
}

let (_val1, _val2) = test();
val1 = _val1;
val2 = _val2;

Usually the two values that are returned from my method are some structures, and in turn they have some methods too, so I want to call methods in those returned structs. Anyway, I use the above pattern a lot, and it becomes cumbersome very fast. Are there any better approaches to do what I want in Rust?

tinker
  • 2,884
  • 8
  • 23
  • 35
  • 1
    Possible duplicate of [Can I destructure a tuple without binding the result to a new variable in a let/match/for statement?](https://stackoverflow.com/questions/34304341/can-i-destructure-a-tuple-without-binding-the-result-to-a-new-variable-in-a-let) – Stefan Dec 30 '17 at 10:43

1 Answers1

1

You can create a macro

macro_rules! assign{
    {($v1:ident, $v2:ident) = $e:expr} =>
    {
        let (v1, v2) = $e;
        $v1 = v1;
        $v2 = v2;
    };
    {($v1:ident, $v2:ident, $v3:ident) = $e:expr} =>
    {
        let (v1, v2, v3) = $e;
        $v1 = v1;
        $v2 = v2;
        $v3 = v3;
    }; // and so on
}

and use it like this

assign!{(val1, val2) = test()};

Playground

red75prime
  • 3,733
  • 1
  • 16
  • 22