Skip to content

Better error messages for missing return values #25228

@yggie

Description

@yggie

I recently ran into an error when writing a Rust program, it was a simple mistake but the compiler warnings were very misleading. I started out with a program much like:

fn foo(bar: usize) -> usize {
    if bar % 5 == 0 {
        return 1;
    }
}

fn main() {
    println!("Hello, {}!", foo(1))
}

It is obvious here that the function foo does not return values for all control paths. The compiler on the other hand, returns something like this:

<anon>:2:5: 4:6 error: mismatched types:
 expected `usize`,
    found `()`
(expected usize,
    found ()) [E0308]
<anon>:2     if bar % 5 == 0 {
<anon>:3         return 1;
<anon>:4     }

Not being a veteran in deciphering the rust compiler messages, it took me a good deal of time to figure out what the real problem was. I think the issue here is that the compiler thinks that the return value is the result of the if expression, which is (). Adding a semicolon after the brace gives a much better error message:

<anon>:1:1: 5:2 error: not all control paths return a value [E0269]
<anon>:1 fn foo(bar: usize) -> usize {
<anon>:2     if bar % 5 == 0 {
<anon>:3         return 1;
<anon>:4     };
<anon>:5 }

In my opinion, this message is much more helpful. I don’t think this scenario is uncommon, and for those like myself who are unfamiliar with the language, it would be a real pain to have to deal with these misleading compiler messages on top of the learning the language. Hopefully this is a quick fix, and it can get in before the official 1.0 release.

PS: I have tested this with for loops and a similar problem occurs.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-diagnosticsArea: Messages for errors, warnings, and lintsC-enhancementCategory: An issue proposing an enhancement or a PR with one.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.WG-diagnosticsWorking group: Diagnostics

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions