简体   繁体   中英

Wrong vector return type for Rust function

pub fn collect_prime_factors(number: i32) -> Vec<i32> {
    let mut prime_factors = Vec::new();

    for i in 2..number {
        if number % i == 0 {
            collect_prime_factors(number / 2);
            prime_factors.push(i);
            prime_factors
        }
    }
}

error:

lib.rs:14:9: 14:22 error: mismatched types:
 expected `()`,
    found `collections::vec::Vec<i32>`
(expected (),
    found struct `collections::vec::Vec`) [E0308]
lib.rs:14         prime_factors

I do not get the problem here. I am declaring a Vec<i32> as return type. Why is the expecting those empty braces?

Why does this not work only when I use it within a loop? When I remove the loop and only return prime_factors; everything works fine.

There are two problems (other than the paste error).

The error you quote is not for the function's return value; it's the value of the if expression :

pub fn collect_prime_factors(number: i32) -> Vec<i32> {
    let mut prime_factors = Vec::new();

    for i in 2..number {
        if number % i == 0 {
            prime_factors.push(i);
            prime_factors   // This would be the value of the if
        }
    }
}

Rust is expecting there to be no return value, or alternatively a value of () , but you're returning prime_factors .

If you fix this, you'll then see that the next error is the reverse, that it's expecting the function to return a Vec<i32> but you're returning () (nothing).

I think the correct thing here is to return the vector at the end of the function once all the factors have been collected:

pub fn collect_prime_factors(number: i32) -> Vec<i32> {
    let mut prime_factors = Vec::new();

    for i in 2..number {
        if number % i == 0 {
            prime_factors.push(i);
        };
    }
    prime_factors  // Return the vector from the function.
}

Playground link

(But this function doesn't actually return only prime factors!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM