Appearance
函数5: exercises/functions/functions5.rs
题目
rust
// functions5.rs
//
// Execute `rustlings hint functions5` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
fn main() {
let answer = square(3);
println!("The square of 3 is {}", answer);
}
fn square(num: i32) -> i32 {
num * num;
}
题目解析
编译器错误信息如下:
txt
⚠️ Compiling of exercises/functions/functions5.rs failed! Please try again. Here's the output:
error[E0308]: mismatched types
--> exercises/functions/functions5.rs:13:24
|
13 | fn square(num: i32) -> i32 {
| ------ ^^^ expected `i32`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
14 | 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`.
我们可以读到的信息如下:
- 类型不匹配
- 函数应该返回i32类型,但是实际返回了单元类型
()
- 这里隐式的返回了单元类型
()
,因为没有return语句 - 同时信息提示我们应该将返回值末尾的
;
去除
由于语句都是返回单元类型()
,所以num*num;
这里是()
Rust的函数返回值有两种形式:
- 一种是:
return num*num;
- 一种是:
num*num
,没有return也没有末尾;
所以有两种修改方式:
rust
fn main() {
let answer = square(3);
println!("The square of 3 is {}", answer);
}
fn square(num: i32) -> i32 {
num * num;
num * num
}
rust
fn main() {
let answer = square(3);
println!("The square of 3 is {}", answer);
}
fn square(num: i32) -> i32 {
num * num;
return num * num;
}
笔记
- 语句都是返回单元类型
()
- 函数的返回值等同于函数体最后一个表达式的值,此时不需要
return
,末尾也不需要加分号;
- 使用 return 关键字和指定值,可从函数中提前返回,此时末尾需要加分号
;