Mismatched types. Expected i32, found () [duplicat

2019-02-25 05:13发布

This code:

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));
    }
}

Has an error during compilation:

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

标签: types rust
1条回答
Explosion°爆炸
2楼-- · 2019-02-25 06:17

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
}

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.

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.

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

查看更多
登录 后发表回答