Warning
This post was published 72 days ago. The information described in this article may have changed.
We all know, that a Rust function returns the unit type () when the function body ends not with an expression but with a statement.
In the official book this is explained a bit un-precise, so we just had a longer discussion in the GitHub issue tracker. Indeed it is difficult to find a precise explanation. One problem is, that some documentation says, that a statement in Rust has no value at all, but other say that a statement has the value of the unit type ().
In my own book, I have the following text:
"Important: Adding a semicolon ; after the final expression [in the function] turns it into a statement. Statements evaluate to the unit type (). If a function is expected to return a value (e.g., -> i32), ending it with a statement like a * b; will result in a type mismatch error, because the function implicitly returns () instead of the expected i32."
I still believe this is correct, but someone in the issue tracker has some doubts, and so I am not fully sure as well.
11 posts - 4 participants
🏷️ rust_feed