Appearance
if2: exercises/if/if2.rs
题目
rust
// if2.rs
//
// Step 1: Make me compile!
// Step 2: Get the bar_for_fuzz and default_to_baz tests passing!
//
// Execute `rustlings hint if2` or use the `hint` watch subcommand for a hint.
// I AM NOT DONE
pub fn foo_if_fizz(fizzish: &str) -> &str {
if fizzish == "fizz" {
"foo"
} else {
1
}
}
// No test changes needed!
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn foo_for_fizz() {
assert_eq!(foo_if_fizz("fizz"), "foo")
}
#[test]
fn bar_for_fuzz() {
assert_eq!(foo_if_fizz("fuzz"), "bar")
}
#[test]
fn default_to_baz() {
assert_eq!(foo_if_fizz("literally anything"), "baz")
}
}
题目解析
根据单元测试,我们知道函数foo_if_fizz
的作用为:
- 当传入
fizz
返回foo
- 当传入
fuzz
返回bar
- 当传入其他,返回
baz
我们再来看编译器给出的信息:
txt
⚠️ Compiling of exercises/if/if2.rs failed! Please try again. Here's the output:
error[E0308]: mismatched types
--> exercises/if/if2.rs:14:9
|
10 | pub fn foo_if_fizz(fizzish: &str) -> &str {
| ---- expected `&str` because of return type
...
14 | 1
| ^ expected `&str`, found integer
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.
我们可以读出的信息为:
- 类型不匹配
- 函数应该返回
&str
类型 - 但是实际返回的是整型(在
1
的地方)
在rust中,条件语句的每个条件块应该返回相同的类型,所以应该这样修改:
rust
pub fn foo_if_fizz(fizzish: &str) -> &str {
if fizzish == "fizz" {
"foo"
} else {
1
}
} else if fizzish == "fuzz" {
"bar"
} else {
"baz"
}
}
笔记
- 在rust中,条件语句的每个条件块应该返回相同的类型