Search code examples
rustquicksort

Expected type did not match the received type


I'm new to rust, and I'm trying to get my hands dirty, so I'm trying to implement quicksort, as part of one of the exercises of "The Book" ( probably the writer didn't intend to suggest to go this deep though, but isn't it the best way to learn? :) )

this is what I have so far:

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())
}

when I try to compile I get this:

[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.

I don't see what I'm screwing up.


Also, I'd be glad to get a complete implementation of quicksort which doesn't use other libraries. Probably I could learn from it.


EDIT: I'm also not sure if this way of "shadowing" with the function name "quicksort" is going to work. I changed it before, so it's not the cause of the error, but I'd like to see if it's going to work this way, that's why I left it like this.


Solution

  • Your fn partition(v: &mut Vec<i32>, lo: i32, hi: i32) is not returning anything (denoted in Rust as having the return type ()), so you cannot assign the result to a variable of type i32.