Skip to content

suggest map_or for simple None substitutions #8492

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
matthiaskrgr opened this issue Mar 1, 2022 · 2 comments · Fixed by #8696
Closed

suggest map_or for simple None substitutions #8492

matthiaskrgr opened this issue Mar 1, 2022 · 2 comments · Fixed by #8696
Assignees
Labels
A-lint Area: New lints

Comments

@matthiaskrgr
Copy link
Member

matthiaskrgr commented Mar 1, 2022

What it does

Find patterns like

pub fn a(s: Option<String>) -> usize {
    match s {
        Some(string) => string.len(),
        None => 1, 
    }
}

and suggest to use map_or instead:

pub fn a(s: Option<String>) -> usize {
    s.map_or(1, |string| string.len())
}

We might need to consider restricting such a lint to simple matches that don't have a lot of "stuff going on"

Lint Name

map_or_match? matching_map_or? mmh

Category

style

Advantage

for simple matches, this reduces lines from 4 to 1, and I think it's a bit easier to grasp what is going on if you are familiar with map_or.

Drawbacks

🤷

We might want to bail out on matches where a single arm spans several lines.

Example

pub fn a(s: Option<String>) -> usize {
    match s {
        Some(string) => string.len(),
        None => 1, 
    }
}

Could be written as:

pub fn a(s: Option<String>) -> usize {
    s.map_or(1, |string| string.len())
}
@Jarcho
Copy link
Contributor

Jarcho commented Mar 2, 2022

Just a note for anyone taking this. There is option_if_let_some_else_none which covers this only for if let ... else ....

@J-ZhengLi
Copy link
Member

Seems like this hasn't been fixed yet... @rustbot claim

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants