[Rust] Implicitly returning values from functions

Code has error:

fn main() {
    let answer = square(3);
    println!("The square of 3 is {}", answer);
}

fn square(num: i32) -> i32 {
    num * num;
}

Error:

⚠️  Compiling of exercises/functions/functions5.rs failed! Please try again. Here's the output:
error[E0308]: mismatched types
  --> exercises/functions/functions5.rs:12:24
   |
12 | fn square(num: i32) -> i32 {
   |    ------              ^^^ expected `i32`, found `()`
   |    |
   |    implicitly returns `()` as its body has no tail or `return` expression
13 |     num * num;
   |              - help: remove this semicolon to return this value

error: aborting due to previous error

For more information about this error, try `rustc --explain E0308`.

 

If we do:

fn square(num: i32) -> i32 {
    num * num
}

That will works, because without ;, Rust consider that line as implicity return value, if you have ;, you need to add returnkeyword:

fn square(num: i32) -> i32 {
    return num * num;
}

 

posted @ 2024-02-23 15:39  Zhentiw  阅读(4)  评论(0编辑  收藏  举报