我正试图在不使用任何std-lib函数的情况下编写一个mem::swap函数。我对rust完全陌生,仍在努力理解如何使用rust语言。
下面是我的代码
fn swap<T: std::fmt::Display>(x: &mut T, y: &mut T) {
unsafe {
// Give ourselves some scratch space to work with
let mut t: &mut T = y;
y = x;
x = t;
}
}
fn main() {
println!("Hello, world!");
let mut x = Box::new(5);
let mut y = Box::new(42);
let mut t = Box::new(0);
swap(&mut x, &mut y);
}
并且我正面临以下错误
error: lifetime may not live long enough
--> src/main.rs:4:29
|
1 | fn swap<T: std::fmt::Display>(x: &mut T, y: &mut T) {
| - - let's call the lifetime of this reference `'2`
| |
| let's call the lifetime of this reference `'1`
...
4 | let mut t: &mut T = y;
| ^ assignment requires that `'2` must outlive `'1`
|
help: consider introducing a named lifetime parameter
|
1 | fn swap<'a, T: std::fmt::Display>(x: &'a mut T, y: &'a mut T) {
| +++ ++ ++
"一生可能活得不够长"是什么意思?有没有一种简单的方法可以在rust中编写mem::swap代码?
您需要Copy
数据。你使用的参考资料对此毫无用处。您需要实际更改x
和y
引用的内容。
例如:
fn swap<T>(a: &mut T, b: &mut T) where T : Copy {
(*a,*b) = (*b, *a)
}
fn main() {
let mut a = 1;
let mut b = 2;
swap(&mut a,&mut b);
println!("a={}, b={}", a, b);
}
如果你在这里设置条件,这真的是一句话,Rust会计算出";临时的";给你的东西。事实上,有一个函数来做这件事实际上有点过头了,因为你可以像往常一样在代码中的任何地方做这一行。
也许您想围绕装箱值进行优化,将Box<T>
作为参数,在这种情况下,您可以在装箱内交换引用,而不是复制,但这是一种专门化。
使用core::ptr::swap
交换原始指针*mut T
怎么样。
use core::ptr::swap;
fn custom_swap<T>(x: &mut T, y: &mut T) {
unsafe {
(x as *mut T).swap(y as *mut T);
}
}
fn main() {
println!("Hello, world!");
let mut x = Box::new(5);
let mut y = Box::new(42);
println!("x={}, y={}", x, y);
custom_swap(&mut x, &mut y);
println!("x={}, y={}", x, y);
}
输出
Hello, world!
x=5, y=42
x=42, y=5