2026年6月4日 星期四

rust 交換兩個 String 變量的值

fn swap_strings(a: &mut String, b: &mut String) {
    let temp = std::mem::take(a);
    *a = std::mem::take(b);
    *b = temp;
}

fn main() {
    let mut s1 = String::from("hello");
    let mut s2 = String::from("world");

    swap_strings(&mut s1, &mut s2);

    println!("{s1}");
    println!("{s2}");
}

沒有留言:

張貼留言