简体   繁体   English

Rust函数的向量返回类型错误

[英]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. 我将Vec<i32>声明为返回类型。 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; 当我删除循环并仅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 : 它是if 表达式的值:

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 . Rust期望没有返回值或()值,但是您正在返回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). 如果解决了这个问题,那么您会看到下一个错误是相反的,它期望函数返回Vec<i32>但是您返回的是() (无)。

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!) (但是此函数实际上并不只返回素因子!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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