如何交换两个数字?

109*_*149 2 rust

我试图在没有任何库的情况下在 Rust 中交换两个整数。

fn main() {
    let mut a = 5;
    let mut b = 6;
    swap(&mut a, &mut b);
    println!("{}, {}", a, b); // expecting 6, 5
}
Run Code Online (Sandbox Code Playgroud)

首先我试过:

fn swap(mut a: &mut u32, mut b: &mut u32) {
    (a, b) = (b, a); // destructuring assignments are not currently supported
}
Run Code Online (Sandbox Code Playgroud)

然后:

fn swap(mut a: &mut u32, mut b: &mut u32) {
    let temp = a;
    a = b;
    b = temp;
}
// got error[E0623]: lifetime mismatch
Run Code Online (Sandbox Code Playgroud)

最后:

fn swap<'a>(mut a: &'a mut u32, mut b: &'a mut u32) {
    let temp = a;
    a = b;
    b = temp;
}
// still does not work; when this scope ends a and b in `main()` are still 5 and 6 respectively
// got warning: value assigned to `a` is never read (for `b` as well)
Run Code Online (Sandbox Code Playgroud)

我不知道怎么了;最后一个实现对我来说看起来很麻烦,但我认为它应该可以工作,因为我正在传递对函数的可变引用,但它不起作用。

C14*_*14L 7

有效的方法:

use std::mem;

let mut x = 5;
let mut y = 42;

mem::swap(&mut x, &mut y);

assert_eq!(42, x);
assert_eq!(5, y);
Run Code Online (Sandbox Code Playgroud)

https://doc.rust-lang.org/std/mem/fn.swap.html

  • @109149,你可以使用 [`core::mem::swap`](https://doc.rust-lang.org/core/mem/fn.swap.html) - 它来自核心库 (6认同)
  • @109149 请在您的问题中包含此类限制,以便人们不会因未能满足您未指定的标准而浪费时间。 (5认同)