rust swap two values
To swap two values in Rust, you can use a temporary variable to hold one of the values while you perform the swap. Here's an example:
fn main() {
let mut a = 5;
let mut b = 10;
let temp = a;
a = b;
b = temp;
println!("a: {}", a); // Output: a: 10
println!("b: {}", b); // Output: b: 5
}
In this example, we have two variables a
and b
with initial values of 5 and 10, respectively. We use the temporary variable temp
to hold the value of a
before swapping it with b
. Finally, we assign the value of temp
(which was the original value of a
) to b
.
This code will swap the values of a
and b
, resulting in a
being 10 and b
being 5.
Please let me know if you need further assistance!