gpt4 book ai didi

rust - 编写通用交换函数

转载 作者:行者123 更新时间:2023-11-29 07:57:05 24 4
gpt4 key购买 nike

我正在尝试学习 Rust 并想编写一个简单的通用交换函数

fn swap<T>(i: &mut T, j: &mut T) {
let tmp: T = *i;
*i = *j;
*j = tmp;
}
fn main() {
let i: &int = &mut 5;
let j: &int = &mut 6;
println!("{} {}", i, j);
swap(i, j);
println!("{} {}", i, j);
}

但是编译器会抛出错误信息:

helloworld.rs:2:18: 2:20 error: cannot move out of dereference of `&mut`-pointer
helloworld.rs:2 let tmp: T = *i;
^~
helloworld.rs:2:9: 2:12 note: attempting to move value to here
helloworld.rs:2 let tmp: T = *i;
^~~
helloworld.rs:2:9: 2:12 help: to prevent the move, use `ref tmp` or `ref mut tmp` to capture value by reference
helloworld.rs:2 let tmp: T = *i;
^~~
helloworld.rs:3:10: 3:12 error: cannot move out of dereference of `&mut`-pointer
helloworld.rs:3 *i = *j;
^~
helloworld.rs:13:10: 13:11 error: cannot borrow immutable dereference of `&`-pointer `*i` as mutable
helloworld.rs:13 swap(i, j);
^
helloworld.rs:13:13: 13:14 error: cannot borrow immutable dereference of `&`-pointer `*j` as mutable
helloworld.rs:13 swap(i, j);
^
error: aborting due to 4 previous errors

我真的是 Rust 的新手,我真的无法以任何方式处理这个错误。希望有人能解释出了什么问题以及原因。

最佳答案

指针取消引用的问题在于它违反了 Rust 的移动语义。您的函数正在借用对 ij 的引用,即使您可以修改借用的值——例如:

fn assign<T>(i: &mut T, j: T) {
*i = j;
}

完全没问题——您不能将借用的值“移动”到其他地方,即使是临时变量。这是因为借用仅在函数调用期间持续,并且通过移动值您将所有权转移给函数,这是不允许的。

解决此问题的一种方法(不使用 unsafe 代码)是复制值而不是移动它。您可以限制 T 实现 Clone 特性,它允许您复制值,而原始借用值保持不变:

fn swap<T: Clone>(i: &mut T, j: &mut T) {
let tmp = i.clone();
*i = j.clone();
*j = tmp;
}
fn main() {
let i: &mut int = &mut 5;
let j: &mut int = &mut 6;
println!("{} {}", i, j);
swap(i, j);
println!("{} {}", i, j);
}

另请注意,我必须制作 ij &mut int,因为在您的代码中您是不变地借用对值的引用。

关于rust - 编写通用交换函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27152779/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com