Appearance
函数3: exercises/functions/functions3.rs
题目
rust
// functions3.rs
//
// Execute `rustlings hint functions3` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
fn main() {
call_me();
}
fn call_me(num: u32) {
for i in 0..num {
println!("Ring! Call number {}", i + 1);
}
}
题目解析
编译器的报错信息如下:
txt
⚠️ Compiling of exercises/functions/functions3.rs failed! Please try again. Here's the output:
error[E0061]: this function takes 1 argument but 0 arguments were supplied
--> exercises/functions/functions3.rs:9:5
|
9 | call_me();
| ^^^^^^^-- an argument of type `u32` is missing
|
note: function defined here
--> exercises/functions/functions3.rs:12:4
|
12 | fn call_me(num: u32) {
| ^^^^^^^ --------
help: provide the argument
|
9 | call_me(/* u32 */);
| ~~~~~~~~~~~
error: aborting due to previous error
For more information about this error, try `rustc --explain E0061`.
编译器信息提示我们:
- 函数有一个参数,但是实际调用没有传递参数
- 提示我们提供num参数
参数类型为u32,我们把调用时的参数加上:
rust
fn main() {
call_me();
call_me(3u32);
}
fn call_me(num: u32) {
for i in 0..num {
println!("Ring! Call number {}", i + 1);
}
}
当然这里我们函数已经声明num
是u32类型,所以我们传递参数时,可以省略类型u32,直接传递3:
rust
fn main() {
call_me();
call_me(3);
}
fn call_me(num: u32) {
for i in 0..num {
println!("Ring! Call number {}", i + 1);
}
}
笔记
在函数签名中,必须声明每个参数的类型。这是 Rust 设计中一个经过慎重考虑的决定:要求在函数定义中提供类型注解,意味着编译器再也不需要你在代码的其他地方注明类型来指出你的意图。而且,在知道函数需要什么类型后,编译器就能够给出更有用的错误消息。