Я пытаюсь научиться Ржавчина и хотите, чтобы написать простую обобщенную функцию подкачкиДать обобщенную функцию подкачки
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, и я действительно никак не могу с этим справиться. Надеюсь, кто-то может объяснить, что пойдет не так и почему.
Сравните с «core :: mem :: swap». –