预期类型与接收到的类型不匹配

Expected type did not match the received type

我是 rust 的新手,我正试图弄脏我的手,所以我正在尝试实现快速排序,作为“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”的“隐藏”方式是否可行。我之前更改过它,所以这不是错误的原因,但我想看看它是否会这样工作,所以我就这样离开了。

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