Appearance
Clippy2: exercises/clippy/clippy2.rs
题目
rust
// clippy2.rs
//
// Execute `rustlings hint clippy2` or use the `hint` watch subcommand for a
// hint.
// I AM NOT DONE
fn main() {
let mut res = 42;
let option = Some(12);
for x in option {
res += x;
}
println!("{}", res);
}
题目解析
错误信息如下:
txt
⚠️ Compiling of exercises/clippy/clippy2.rs failed! Please try again. Here's the output:
Checking clippy2 v0.0.1 (/home/jeffery/dev/rust/rustlings/exercises/clippy)
error: for loop over an `Option`. This is more readably written as an `if let` statement
--> clippy2.rs:11:14
|
11 | for x in option {
| ^^^^^^
|
= note: `-D for-loops-over-fallibles` implied by `-D warnings`
help: to check pattern in a loop use `while let`
|
11 | while let Some(x) = option {
| ~~~~~~~~~~~~~~~ ~~~
help: consider using `if let` to clear intent
|
11 | if let Some(x) = option {
| ~~~~~~~~~~~~ ~~~
error: could not compile `clippy2` (bin "clippy2") due to previous error
信息提示我们,其实可以用while let
或者if let
来实现。
rust
fn main() {
let mut res = 42;
let option = Some(12);
for x in option {
while let Some(x) = option {
res += x;
}
println!("{}", res);
}
或者
rust
fn main() {
let mut res = 42;
let option = Some(12);
for x in option {
if let Some(x) = option {
res += x;
}
println!("{}", res);
}