Skip to content

enhancement to if_let_some_result: apply to while loops as well #7594

Closed
@dllu

Description

@dllu

What it does

Where res is a Result,

while let Some(a) = res.ok() {

should be rewritten as

while let Ok(a) = res {

This could either be an enhancement to if_let_some_result or have a new name like while_let_some_result.

SEE ALSO: #7586 where previously clippy suggested an incorrect fix (changing while to if). In that thread, @camsteffen suggested creating a new issue for this.

Categories (optional)

  • Kind: style

What is the advantage of the recommended code over the original code

Conciseness etc.

It maintains consistency with the existent if_let_some_result and has the same advantages, except now for while loops too.

Drawbacks

None.

Example

struct Wat {
    counter: i32,
}

impl Wat {
    fn next(&mut self) -> Result<i32, &str> {
        self.counter += 1;
        if self.counter < 5 {
            Ok(self.counter)
        } else {
            Err("Oh no")
        }
    }
}

fn main() {
    let mut wat = Wat { counter: 0 };
    while let Some(a) = wat.next().ok() { // <---- here
        dbg!(&a);
    }
}

Could be written as:

    while let Ok(a) = wat.next() {

Metadata

Metadata

Assignees

Labels

C-enhancementCategory: Enhancement of lints, like adding more cases or adding help messagesgood first issueThese issues are a good way to get started with Clippy

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions