【问题标题】:Calculating prime numbers in Rust在 Rust 中计算素数
【发布时间】:2019-04-22 07:11:07
【问题描述】:

我正在尝试在 Rust 中计算素数,但遇到了一些问题。我得到两个错误。我不明白这个值是如何返回到主函数的。

fn main() {
    let x = is_prime(25); //function calling
    println!("{}", x);
}

fn is_prime(n: u32) -> bool {
    let mut result: bool = for a in 2..n {
        result = if n % a == 0 { false } else { true };
    };
    result
}
error[E0425]: cannot find value `result` in this scope
 --> src/main.rs:8:9
  |
8 |         result = if n % a == 0 { false } else { true };
  |         ^^^^^^ not found in this scope
help: possible candidates are found in other modules, you can import them into scope
  |
1 | use futures::future::result;
  |
1 | use tokio::prelude::future::result;
  |

error[E0308]: mismatched types
 --> src/main.rs:7:28
  |
6 |   fn is_prime(n: u32) -> bool {
  |                          ---- expected `bool` because of return type
7 |       let mut result: bool = for a in 2..n {
  |  ____________________________^
8 | |         result = if n % a == 0 { false } else { true };
9 | |     };
  | |_____^ expected bool, found ()
  |
  = note: expected type `bool`
             found type `()`

【问题讨论】:

    标签: rust


    【解决方案1】:

    您的代码的问题是您在定义变量时使用了变量result

    ...
    let mut result: bool = for a in 2..n { // declared here
        result = if n % a == 0 { // used here, but it is still not initialized
    ...
    

    没有result 变量你可以轻松做到,不是必须的:

    fn is_prime(n: u32) -> bool {
        if n <= 1 {
            return false;
        }
        for a in 2..n {
            if n % a == 0 {
                return false; // if it is not the last statement you need to use `return`
            }
        }
        true // last value to return
    }
    

    Playground link

    【讨论】:

    • 这里真的不需要match 语句; if n % a == 0 { return false; } 更简单,避免了额外的continue。整个函数可以是!(2..n).any(|a| n % a == 0)(2..n).all(|a| n % a != 0)
    【解决方案2】:

    您的代码中有几个问题(忽略它无法编译):

    • 你覆盖了结果 -> 想象n = 4。当你除以 2 时,你得到 result = true,但在下一次迭代中,当你除以 3 时,你得到 result = false
    • 如果n&lt;=2 你的循环永远不会被执行,那么结果会是什么

    不要尝试使用任何新的语法,而是尝试将其编写为尽可能可读:

    fn is_prime(n: u32) -> bool {
        let limit = (n as f64).sqrt() as u32;
    
        for i in 2..=limit {
            if n % i == 0 {
                return false;
            }
        }
    
        true
    }
    

    【讨论】:

    • 块末尾的显式 return 语句是非惯用的。请参阅other comment,它展示了如何使用迭代器方法而不是显式编写 for 循环。
    • 这是 Rust 中最让我烦恼的事情 - 我真的很讨厌能够以两种不同的方式进行如此简单的操作。
    • @SveltinZarev return 关键字是必要的,因此您可以在返回值的同时尽早退出函数,因此我不知道如何将其从语言中完全删除,尽管这可能是编译器警告,“不要在函数的最终语句/表达式中使用return”? ?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 2014-05-21
    • 2019-06-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多