Ranj
Ranj

Reputation: 788

Error mismatched types: expected 'collections::vec::Vec<i32>', found '&collections::vec::Vec<i32>'

I'm trying to use selection_sort to create a sorted vector while keeping the original unsorted vector:

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
}

Error:

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

Upvotes: 1

Views: 10395

Answers (1)

Shepmaster
Shepmaster

Reputation: 430663

Your question can be simplified to this (please review and follow how to create an MCVE when asking questions here):

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

You are accepting a reference to a type and trying to return it as not-a-reference. That simply is a straight-forward type error, the same as this:

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

T and &T are different types.

Ultimately, your code doesn't make sense right now. To make a &Vec<T> into a Vec<T>, you'd need to clone it:

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
}

But 99.99% of the time, it doesn't make sense to accept a &Vec<T>; accept a &[T] instead:

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

Upvotes: 9

Related Questions