Appearance
函数2: exercises/functions/functions2.rs
题目
rust
// functions2.rs
//
// Execute `rustlings hint functions2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
fn main() {
call_me(3);
}
fn call_me(num:) {
for i in 0..num {
println!("Ring! Call number {}", i + 1);
}
}
题目解析
编译器报错信息如下:
txt
⚠️ Compiling of exercises/functions/functions2.rs failed! Please try again. Here's the output:
error: expected type, found `)`
--> exercises/functions/functions2.rs:12:16
|
12 | fn call_me(num:) {
| ^ expected type
error[E0425]: cannot find value `num` in this scope
--> exercises/functions/functions2.rs:13:17
|
13 | for i in 0..num {
| ^^^ not found in this scope
|
help: you might have meant to write `.` instead of `..`
|
13 - for i in 0..num {
13 + for i in 0.num {
|
error: aborting due to 2 previous errors
For more information about this error, try `rustc --explain E0425`.
根据错误信息,首先提示我们num
没有指定类型,第二个在当前作用域没有找到num。
从函数调用call_me(3);
我们知道num
应该是i32类型,这里需要注意,变量绑定时如果没有写明类型,Rust会自动推导,但是在函数定义中,我们必须指定参数的类型,避免歧义。
我们先指定num
的类型为i32:
rust
fn main() {
call_me(3);
}
fn call_me(num:) {
fn call_me(num: i32) {
for i in 0..num {
println!("Ring! Call number {}", i + 1);
}
}
编译顺利通过。
笔记
- 我们可以定义为拥有参数(parameters)的函数,参数是特殊变量,是函数签名的一部分。
- 在函数签名中,必须声明每个参数的类型。