类型不匹配.预期 i32,找到 () [英] Mismatched types. Expected i32, found ()

查看:44
本文介绍了类型不匹配.预期 i32,找到 ()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

fn ackermann(m: i32, n: i32) -> i32 {
    if m == 0 {
        return n + 1;
    } else if m > 0 && n == 0 {
        return ackermann(m - 1, 1);
    } else if m > 0 && n > 0 {
        return ackermann(m - 1, ackermann(m, n - 1));
    }
}

编译时出错:

error: mismatched types [--explain E0308]
 --> src/main.rs:3:5
  |>
3 |>     if m == 0 {
  |>     ^ expected i32, found ()
note: expected type `i32`
note:    found type `()`

推荐答案

并非所有代码路径都返回值.您可以通过几种方法解决此问题.. 但由于这似乎是一个递归函数.. 您可能想要一种方法来打破递归:

Not all of your code paths return a value. You can fix this a few ways.. but since this appears to be a recursive function.. you probably want a way to break the recursion:

fn ackermann(m: i32, n: i32) -> i32 {
    if m == 0 {
        return n + 1;
    } else if m > 0 && n == 0 {
        return ackermann(m - 1, 1);
    } else if m > 0 && n > 0 {
        return ackermann(m - 1, ackermann(m, n - 1));
    }

    return 0; // This breaks your recursion
}

或者,也许是一个显式的else:

Or, perhaps an explicit else:

if m == 0 {
    return n + 1;
} else if m > 0 && n == 0 {
    return ackermann(m - 1, 1);
} else if m > 0 && n > 0 {
    return ackermann(m - 1, ackermann(m, n - 1));
} else { // An explicit else also works
    return 0;
}

我没有过多考虑这个算法是/做什么..但错误很明显.如何中断递归并让函数返回实际值取决于您.

I haven't put much thought into what this algorithm is/does.. but the error is pretty clear. How you break your recursion and have the function return an actual value is up to you.

编辑:Benjamin 在评论中指出,此特定函数实际上不应超出您提供的条件.因此,一些其他选项包括如果代码确实退出或可能返回 Result 而导致恐慌.

EDIT: Benjamin has pointed out in the comments that this specific function should not actually reach outside of the conditionals you've provided. As such, some other options include panic'ing if the code does get out or perhaps returning Result<i32> instead.

TLDR 是:如果您的任何条件都不满足.. 那么该函数在预期返回数字时将不会返回任何内容.

The TLDR is: if none of your conditionals are met.. then the function won't return anything when its expected to return a number.

这篇关于类型不匹配.预期 i32,找到 ()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆