Introduction
This is a number swapping operation without using a temp variable written in Rust.
A swap with a temp variable would look like this:
|
|
This creates another temp variable to contain either values in a
or b
, followed by doing the actual swap, and reassigning the value in the temp variable to the second variable.
This causes a slight waste of space as a temp variable of greater or equal size to the larger of the 2 variables is needed to do the swap.
A space efficient is to use mathematical operations +
, -
, *
, /
or Bitwise XOR
to do the swap.
Code
|
|
|
|
The above uses multiple methods to do a swap between 2 variables. However, this is not foolproof.
Potential Issues
Overflow
If either of the variables are larger than the specified type (i32
), there will be an overflow of variables:
|
|
|
|
Divide by zero
swap3
uses multiplication and division for the swap. Exception handling is required to prevent a divide by zero
error, if either of a
or b
is zero.
|
|
|
|
A match
is done to prevent the use of the function if either numbers are zero:
|
|