Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rust tuple assignment

Tags:

rust

I have the following scenario:

use num_bigint::BigUint;

fn add_one(px: BigUint, py: BigUint) -> (BigUint, BigUint) {
    (px+1u32, py+1u32)
}

fn test(x: &[u8], y: &[u8]) {
    let mut x = BigUint::from_bytes_le(x);
    let mut y = BigUint::from_bytes_le(y);

    (x,y) = add_one(x, y);
}

When I try to compile I get the following compile error:

error[E0658]: destructuring assignments are unstable
  --> src/lib.rs:76:11
   |
76 |     (x,y) = ecc_add(x, y);
   |     ----- ^
   |     |
   |     cannot assign to this expression
   |
   = note: see issue #71126 <https://github.com/rust-lang/rust/issues/71126> for more information

What does this mean? let (x,y) = add_one(x, y); seems to fix the error, but I think this will not mutate the original x and y variable (?) and I want to avoid creating any temporary variables. I get the same error when using (x, y) = (x+1u32, y+1u32);

If I instead use a single return value, it works fine:

use num_bigint::BigUint;

fn add_one(px: BigUint) -> BigUint {
    px+1u32
}

fn test(x: &[u8]) {
    let mut x = BigUint::from_bytes_le(x);

    x = add_one(x)
}

How do I assign x and y to the return value of add_one ?

like image 709
Kevin Avatar asked Sep 03 '26 19:09

Kevin


2 Answers

Destructuring assignments like that are an unstable feature, prone to changes and removal, so you cannot use it in stable rust. Destructuring assignment is now stable.

Just use let (x,y) = .... "Too many temporary variables" is not a concern you should be worrying about (without profiling, at least), especially since the old x and y variables have been moved out of. Let the compiler worry about reusing space; it can do a better job than you can.

like image 51
Colonel Thirty Two Avatar answered Sep 07 '26 02:09

Colonel Thirty Two


As of Rust version 1.59, this is a stable feature, and your original implementation will work. See here for more information: https://blog.rust-lang.org/2022/02/24/Rust-1.59.0.html#destructuring-assignments.

like image 27
henrikig Avatar answered Sep 07 '26 02:09

henrikig