Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mismatched types. Expected i32, found () [duplicate]

Tags:

types

rust

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 `()`
like image 779
Brady Dean Avatar asked Sep 16 '16 00:09

Brady Dean


1 Answers

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.

like image 127
Simon Whitehead Avatar answered Nov 09 '22 10:11

Simon Whitehead