How to swap two strings

I've just finished reading " What Is Ownership?" section of the book.
I remember writing a C swap function to swap two integers that involves using a temp variable and parameters having to be pointers.
Now I want to use Rust to swap two different strings. (That seems impossible in C)
Here is the code.

fn main() {
    let s1 = String::from("Hello");
    let s2 = String::from("World");
    println!("{} {}", s1, s2);
    let (s1, s2) = swap(s1, s2);
    println!("{} {}", s1, s2);
}
fn swap(s1: String, s2: String) -> (String, String) {
    (s2, s1) 
}

After compiling and running, I get what I want to see happen.
But the code I write makes me feel weird as no temp variable is used and the s1 s2 which are assigned the second time are different from the previous s1 and s2 .
I think that's not actually swapped.
Any better ideas to write swap strings?

The standard library has a general-purpose swap function you can use:

std::mem::swap(&mut s1, &mut s2);

If you use this function and compile your code in release mode, you can see that it does indeed allocate and use a temporary variable that is 24 bytes large, just as big as a String. Check it out here.

1 Like

How would this differ in C from the case of swapping integers? Strings are just pointers, and can be assigned just as integers are.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.