Skip to content

add Result to question_mark #7135

Closed
@TheAlgorythm

Description

@TheAlgorythm

What it does

The lint should hint to flatten the error propagation from using match/if let to a more readable declarative propagation with the ? operator.

Categories

  • Kind: clippy::style, maybe clippy::pedantic

The control structures distract in the flow of reading and therefore the ? operator was created. A comprehensive list of arguments can be found in the documentation of Rust

Drawbacks

As long as only the Err will always return an Err, there should be no false-positives.

Example

fn propagate_match_input(input: Result<String, u64>) -> Result<String, u64> {
    let inner = match input {
        Ok(inner) => inner,
        Err(code) => return Err(code),
    };

    Ok(inner)
}

fn match_input(input: Result<String, u64>) -> Result<String, bool> {
    let inner = match input {
        Ok(inner) => inner,
        Err(code) => return Err(code != 0),
    };

    Ok(inner)
}

fn if_let_input(input: Result<String, u64>) -> Result<(), bool> {
    if let Err(code) = input {
        return Err(code != 0);
    }

    Ok(())
}

Could be written as:

fn propagate_match_input(input: Result<String, u64>) -> Result<String, u64> {
    let inner = input?;

    Ok(inner)
}

fn match_input(input: Result<String, u64>) -> Result<String, bool> {
    let inner = input.map_err(|code| code != 0)?;

    Ok(inner)
}

fn if_let_input(input: Result<String, u64>) -> Result<(), bool> {
    input.map_err(|code| code != 0)?;

    Ok(())
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-enhancementCategory: Enhancement of lints, like adding more cases or adding help messagesL-styleLint: Belongs in the style lint groupgood 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