首页 > 解决方案 > 预期类型与收到的类型不匹配

问题描述

我是生锈的新手,我正试图弄脏我的手,所以我试图实现快速排序,作为“The Book”练习之一的一部分(可能作者不打算建议虽然如此深入,但这不是最好的学习方式吗?:))

这就是我到目前为止所拥有的:

fn quicksort(v: &mut Vec<i32>) {
    // helper funtions for sorting the partitional vectors
    
    fn partition(v: &mut Vec<i32>, lo: i32, hi: i32) {
    // pivot
    let mut p: i32;
    let mut i = lo;

    for j in i..hi {
    }
    }
    
    fn quicksort(v: &mut Vec<i32>, lo: i32, hi: i32) {
    // pivot
    let mut p: i32;
    if lo < hi {
        p = partition(v, lo, hi);
    }
    }


    quicksort(v, 0, (v.len() -1).try_into().unwrap())
}

当我尝试编译时,我得到了这个:

[foo12@archT520 vectors]$ cargo run
   Compiling vectors v0.1.0 (/home/foo12/programs/rust/book/vectors)
error[E0308]: mismatched types
  --> src/main.rs:36:10
   |
36 |         p = partition(v, lo, hi);
   |             ^^^^^^^^^^^^^^^^^^^^ expected `i32`, found `()`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.
error: could not compile `vectors`

To learn more, run the command again with --verbose.

我不明白我在搞砸什么。


另外,我很高兴获得不使用其他库的快速排序的完整实现。或许我可以从中吸取教训。


编辑:我也不确定这种使用函数名称“quicksort”的“阴影”方式是否可行。我之前更改过它,所以这不是错误的原因,但我想看看它是否会这样工作,这就是我这样离开它的原因。

标签: rustquicksort

解决方案


fn partition(v: &mut Vec<i32>, lo: i32, hi: i32)没有返回任何东西(在 Rust 中表示为具有返回类型()),所以你不能将结果分配给类型的变量i32


推荐阅读