avatarJohn Philip

Summarize

Rustlings: clippy2.rs #Issue85 — Clippy in Rust

Rustlings Challenge: clippy2.rs Solution Walkthrough

Image by Brave

This is the Eighty-fifth (85th) issue of the Rustlings series. In this issue, we provide solutions to Rustlings exercises along with detailed explanations. In this issue we will solve the challenge on clippy2.rs.

Previous challenge #Issue 84

The Clippy tool is a collection of lints to analyze your code so you can catch common mistakes and improve your Rust code.

Challenge:

// 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);
}

Explanation:

When we run the code, it will throw the error below.

11 |     for x in option {
   |              ^^^^^^
   |
   = note: `#[warn(for_loops_over_fallibles)]` on by default
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 {

Solution:

The warning message is suggesting that we use while let or if let instead of a for loop when working with an Option. This helps make our intent more explicit.

fn main() {
    let mut res = 42;
    let option = Some(12);
    if let Some(x) = option {
        res += x;
    }
    println!("{}", res);
}

In our solution, we use an if let statement to explicitly handle the Some case when working with the option variable. This makes it clear that we’re checking for the presence of a value and updating res accordingly.

You can experiment with the code on Rust Playground.

Resources

Before you go

Thank you for taking the time to read through this challenge. We invite you to share your knowledge of Rust as well. If you found this article valuable, please don’t hesitate to share it with others. Don’t forget to follow the publication and give the article some claps 👏.

Thank you, and we look forward to seeing you for the next challenges!

More reads

Rust
Rustlang
Rust Programming Language
Programming
Software Development
Recommended from ReadMedium