use*_*211 1 type-mismatch rust
我正在尝试使用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
}
Run Code Online (Sandbox Code Playgroud)
错误:
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`.
Run Code Online (Sandbox Code Playgroud)
您的问题可以简化为此(请在此处提问时查看并了解如何创建MCVE):
fn selection_sort(vector: &Vec<i32>) -> Vec<i32> {
vector
}
Run Code Online (Sandbox Code Playgroud)
您正在接受对类型的引用并尝试将其作为非引用返回.这只是一个直接的类型错误,与此相同:
fn something(value: &u8) -> u8 {
value
}
Run Code Online (Sandbox Code Playgroud)
T并且&T是不同的类型.
最终,您的代码现在没有意义.要&Vec<T>成为a 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
}
Run Code Online (Sandbox Code Playgroud)
但99.99%的时间,接受一个没有意义&Vec<T>; 接受一个&[T]代替:
fn selection_sort(vector: &[i32]) -> Vec<i32> {
let mut vector = vector.to_vec();
// ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1084 次 |
| 最近记录: |