我试图在没有任何库的情况下在 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)
我不知道怎么了;最后一个实现对我来说看起来很麻烦,但我认为它应该可以工作,因为我正在传递对函数的可变引用,但它不起作用。
有效的方法:
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
| 归档时间: |
|
| 查看次数: |
194 次 |
| 最近记录: |