【问题标题】:Error mismatched types: expected 'collections::vec::Vec<i32>', found '&collections::vec::Vec<i32>'错误类型不匹配:预期 'collections::vec::Vec<i32>',发现 '&collections::vec::Vec<i32>'
【发布时间】:2015-10-30 15:30:33
【问题描述】:

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

【问题讨论】:

    标签: rust type-mismatch


    【解决方案1】:

    您的问题可以简化为(请在此处提问时查看并遵循如何创建MCVE):

    fn selection_sort(vector: &Vec<i32>) -> Vec<i32> {
        vector
    }
    

    您正在接受对类型的引用并尝试将其作为非引用返回。这只是一个直接的类型错误,与此相同:

    fn something(value: &u8) -> u8 {
        value
    }
    

    T&amp;T 是不同的类型。

    最终,您的代码现在没有意义。要将&amp;Vec&lt;T&gt; 变成Vec&lt;T&gt;,您需要克隆它:

    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% 的情况下,接受 &amp;Vec&lt;T&gt; 是没有意义的;改为接受&amp;[T]

    fn selection_sort(vector: &[i32]) -> Vec<i32> {
        let mut vector = vector.to_vec();
        // ...
    }
    

    【讨论】:

    • 那会节省我很多打字的时间.. 无论如何我明白这两者是不同的类型,但我不明白如何复制它的值
    • 所以如果我理解正确的话,最好使用向量的参考切片而不是向量的参考。制作一个向量的切片不是额外的计算吗?如果我使用参考向量与参考切片是正确的,则使用相同数量的内存
    • 从对向量的引用创建切片非常便宜。切片是指向数据的直接指针,&amp;Vec 对接受它的函数有一个额外的间接。
    • 谢谢两位,你们的回复很有用
    • 实际上,&amp;[T] takes more space&amp;Vec&lt;T&gt;。从技术上讲,我确实认为这是一个 tiny 更多的计算,但它更能接受各种类型(Vec 和数组,仅举两个例子)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多