-
Notifications
You must be signed in to change notification settings - Fork 12.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Better error messages for missing return values #25228
Comments
It does, actually. I personally think this is too much of a special case for an error, but someone else might feel differently. |
In addition to what @steveklabnik said, I should add we already have a special diagnostic for fn main() {
if true {
0
} else if false {
1
};
}
But it doesn't kick in if you drop the trailing |
Triage: no change |
With a single
|
Current output for the last case presented:
|
#58981 will provide the similar output for the original case as we already do for the prior comment:
|
Point at coercion reason for `if` expressions without else clause if caused by return type ``` error[E0317]: if may be missing an else clause --> $DIR/if-without-else-as-fn-expr.rs:2:5 | LL | fn foo(bar: usize) -> usize { | ----- found `usize` because of this return type LL | / if bar % 5 == 0 { LL | | return 3; LL | | } | |_____^ expected (), found usize | = note: expected type `()` found type `usize` = note: `if` expressions without `else` must evaluate to `()` ``` Fix #25228.
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:
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: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: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.The text was updated successfully, but these errors were encountered: