Return Type Syntax Woes

Rustlings functions4.rs made me notice several things.

This gives an unrusty, very terse error message with no suggestion:

fn sale_price(price: i64) -> {
    if is_even(price) {
        price - 10
    } else {
        price - 3
    }
}
Syntax Error: expected type rust-analyzer(syntax-error)

Same error from user’s perspective, but removing the arrow dramatically improves the message:

error[E0308]: mismatched types
  --> exercises/02_functions/functions4.rs:13:9
   |
11 | fn sale_price(price: i64) {
   |                          - help: try adding a return type: `-> i64`
12 |     if is_even(price) {
13 |         price - 10
   |         ^^^^^^^^^^ expected `()`, found `i64`

In both cases VScode doesn’t suggest the obvious quick fix.

1 Like

It looks like a rust-analyzer or IDE issue. The compiler's message is good:

error: expected type, found `{`
 --> src/lib.rs:1:30
  |
1 | fn sale_price(price: i64) -> {
  |                              ^ expected type

Playground

5 Likes

Looks better. Not offering me the full compiler output is surely on their side. (And I hope they also see and fix this.)

I do understand that one is syntax level and the other comes later, at type level. Nonetheless, from a user and specially beginner perspective (this is from what Rustlings confronts them with) those are two nuances of pretty much the same error. And only one makes Rust easy and endearing, by giving a concrete suggestion.

And even then the message format seems to somehow differ from others. VScode usually can pick up the suggested fix, but not here.

I'm not sure how frequently Rust-Analyzer maintainers read this forum -- I suggest you open a GitHub issue against Rust-Analyzer for this.