gpt4 book ai didi

rust - 错误不匹配的类型 : expected 'collections::vec::Vec' , 找到 '&collections::vec::Vec'

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

我正在尝试使用 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`.

最佳答案

您的问题可以简化为(请在此处提问时查看并遵循如何创建 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();
// ...
}

关于rust - 错误不匹配的类型 : expected 'collections::vec::Vec<i32>' , 找到 '&collections::vec::Vec<i32>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33439574/

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