Reason of the error expected (), found struct `std::vec::Vec` in Rust?

你说的曾经没有我的故事 提交于 2020-11-29 18:55:51

问题


I am new to rust programming. I wanted to implement merge sort with recursion. Here is my code:

fn merge(a: &mut Vec<u32>, b: &mut Vec<u32>) -> Vec<u32> {
    let mut temp: Vec<u32> = Vec::new();

    println!("The digit is {}", a[0]);
    while a.len() > 0 && b.len() > 0 {
        if a[0] > b[0] {
            temp.push(a[0]);
            a.pop();
        } else {
            temp.push(b[0]);
            b.pop();
        }
    }

    while a.len() > 0 {
        temp.push(a[0]);
        a.pop();
    }

    while b.len() > 0 {
        temp.push(b[0]);
        b.pop();
    }

    temp
}

fn merge_sort(v: &mut Vec<u32>) -> Vec<u32> {
    println!("The divided vector is: {:?}", v);
    let n = v.len();

    if n == 1 {
        println!("The divided vector is: {:?}", v.to_vec());
        let t: Vec<u32> = Vec::new();
        t.push(v[0]);
        t
    }

    if n == 0 {
        panic!("Alas!! NULL");
    }

    merge(
        &mut merge_sort(&mut v[0..n / 2].to_vec()),
        &mut merge_sort(&mut v[n / 2 + 1..n].to_vec()),
    )
    .to_vec()
}

fn main() {
    let mut v = vec![23, 78, 89, 64, 23, 12, 79, 45, 64];
    println!("The vector is: {:?}", v);
    println!("The length {}", v.len());

    let v = merge_sort(&mut v);

    println!("The sorted vector is: {:?}", v);
}

The problem is, when I am trying to compile it, I am getting the following error:

error[E0308]: mismatched types
  --> src/main.rs:36:9
   |
32 | /     if n == 1 {
33 | |         println!("The divided vector is: {:?}", v.to_vec());
34 | |         let t: Vec<u32> = Vec::new();
35 | |         t.push(v[0]);
36 | |         t
   | |         ^ expected `()`, found struct `std::vec::Vec`
37 | |     }
   | |     -- help: consider using a semicolon here
   | |_____|
   |       expected this to be `()`
   |
   = note: expected unit type `()`
                 found struct `std::vec::Vec<u32>`

Do you have any idea why am I getting this strange error! It seems, I am missing something.


回答1:


In Rust, the block type is the type of the final expression or () if there is none. Also combined blocks needs to be same type like if{...} else if{...} else{...}. Without an else the return type of an if expression must be () as this is the type that is returned when the expression evaluates to false.

Additionally the result is not the final expression in your code. What you need instead is to use return. Also be aware Vec::push requires a mutable reference of instance(&mut self).

if n == 1 {
    println!("The divided vector is: {:?}", v.to_vec());
    let mut t: Vec<u32> = Vec::new();
    t.push(v[0]);
    return t;
}


来源:https://stackoverflow.com/questions/60772160/reason-of-the-error-expected-found-struct-stdvecvec-in-rust

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!