我正在尝试使用selection_sort
创建一个排序向量,同时保留原始未排序的向量:
fn main() {
let vector_1: Vec<i32> = vec![15, 23, 4, 2, 78, 0];
let sorted_vector = selection_sort(&vector_1);
println!("{:?} is unsorted, \n{:?} is sorted.", &vector_1, &sorted_vector);
}
fn selection_sort(vector_1: &Vec<i32>) -> Vec<i32> {
let mut vector = vector_1;
let start = 0;
while start != vector.len() {
for index in (start .. vector.len()) {
match vector[index] < vector[start] {
true => vector.swap(index, start),
false => println!("false"), // do nothing
}
}
start += 1;
}
vector
}
错误:
Compiling selection_sort v0.1.0 (file:///home/ranj/Desktop/Rust/algorithms/sorting/selection_sort)
src/main.rs:21:5: 21:11 error: mismatched types:
expected `collections::vec::Vec<i32>`,
found `&collections::vec::Vec<i32>`
(expected struct `collections::vec::Vec`,
found &-ptr) [E0308]
src/main.rs:21 vector
^~~~~~
src/main.rs:21:5: 21:11 help: run `rustc --explain E0308` to see a detailed explanation
error: aborting due to previous error
Could not compile `selection_sort`.
答案 0 :(得分:5)
您的问题可以简化为此(请在此处提问时查看并了解如何创建MCVE):
fn selection_sort(vector: &Vec<i32>) -> Vec<i32> {
vector
}
您接受对类型的引用并尝试将其作为非引用返回。这只是一个直接的类型错误,与此相同:
fn something(value: &u8) -> u8 {
value
}
T
和&T
是不同的类型。
最终,您的代码现在没有意义。要将&Vec<T>
变为Vec<T>
,您需要克隆它:
fn selection_sort(vector: &Vec<i32>) -> Vec<i32> {
let mut vector = vector.clone();
let mut start = 0;
while start != vector.len() {
for index in (start .. vector.len()) {
match vector[index] < vector[start] {
true => vector.swap(index, start),
false => println!("false"), // do nothing
}
}
start += 1;
}
vector
}
但99.99%的时间,接受&Vec<T>
是没有意义的;接受&[T]
代替:
fn selection_sort(vector: &[i32]) -> Vec<i32> {
let mut vector = vector.to_vec();
// ...
}