Here, we are going to learn about Program to swap Two Numbers in Rust with This Step-by-Step Guide in details.
There are many ways to Program to swap Two Numbers in Rust which are given below:
Method 1: Using the std::mem::swap
Function
Rust provides a built-in function for swapping two mutable variables called std::mem::swap
. This function takes two mutable references and swaps their values.
Example:
use std::mem;
fn main() {
let mut a = 5;
let mut b = 10;
println!("Before swap: a = {}, b = {}", a, b);
mem::swap(&mut a, &mut b);
println!("After swap: a = {}, b = {}", a, b);
}
This method is more idiomatic and recommended, as it ensures memory safety and readability. The std::mem::swap
function takes care of the underlying implementation, allowing you to focus on your program logic.
Method 2: Using a Temporary Variable
This is the straightforward approach to swapping two numbers by using a temporary variable. Here’s how to implement it in Rust:
fn main() {
let mut a = 5;
let mut b = 10;
println!("Before swap: a = {}, b = {}", a, b);
let temp = a;
a = b;
b = temp;
println!("After swap: a = {}, b = {}", a, b);
}
In this example, we first define two mutable variables, a
and b
, then store the value of a
in a temporary variable called temp
. Next, we assign the value of b
to a
and the value of temp
to b
. Finally, we print the values of a
and b
after the swap.
Method 3: Using XOR Bitwise Operator
We can swap two numbers is by using the XOR bitwise operator. This method doesn’t require a temporary variable thus reducing memory usage:
fn main() {
let mut a = 5;
let mut b = 10;
println!("Before swap: a = {}, b = {}", a, b);
a = a ^ b;
b = a ^ b;
a = a ^ b;
println!("After swap: a = {}, b = {}", a, b);
}
In this example, we apply the XOR operator (^) to a
and b
three times. The first operation stores the XOR result in a
, the second one in b
, and the third one in a
again. The numbers are then swapped without using an extra variable.
To learn more about Rust language, please follow given below link.
https://techieindoor.com/rust-a-deep-dive-into-rust-with-examples/
References:
https://en.wikipedia.org/wiki/Rust_(programming_language)