OneBite.Dev - Coding blog in a bite size

Swap A String In Rust

Code snippet for how to Swap A String In Rust with sample and detail explanation

In this article, we will explore how to swap a string in Rust. Rust, a systems programming language, has built-in support for a variety of operations, including string swapping.

Code Snippet: Swapping Strings in Rust

Without further ado, let’s dive straight into the code:

func main(){
    let mut string1 = String::from("Hello");
    let mut string2 = String::from("World");
  
    println!("Before swap: String1: {}, String2: {}", string1, string2);
  
    std::mem::swap(&mut string1, &mut string2);
  
    println!("After swap: String1: {}, String2: {}", string1, string2);
}

Code Explanation: Swapping Strings in Rust

In this tutorial, we’ll decode the above Rust code for swapping two strings.

In Rust, we first define the two strings string1 and string2 that we need to swap. In this case, their initial values are “Hello” and “World” respectively. We then print these strings to the console before swapping with the println! macro. The {} placeholders will be replaced by the string variables string1 and string2.

Next comes the crucial part: the std::mem::swap function. This function takes in two mutable references to string1 and string2 and swaps their values. You need to note that, in Rust, we use &mut keyword to declare mutable references.

Finally, we print out string1 and string2 again, after the swap. At this point, if the code has worked correctly, the initial value of string1 (“Hello”) should have been transferred to string2, and vice versa. Hence, the output should display: “After swap: String1: World, String2: Hello”.

Swapping strings in Rust may appear intricate at first look; however, with the std::mem::swap function and Rust’s mutable reference system, it becomes quite a straightforward task. So, keep practicing and stay tuned for more Rust how-tos!

rust