Skip to content

Replace self-calling closures with try blocks (once stabilized) #6426

Open
@kangalio

Description

@kangalio

What it does

In one of my codebases, I regularly used lambdas and immediately called them, to handle nested optional types:

let nested_property: Option<C> = (|| Some(object.a?.b?.c?))();

Once try blocks are stabilized, this can be done much cleaner and more idiomatically:

let nested_property: Option<C> = try { object.a?.b?.c? };

Another example:

let property = (|| Some(string.get(5..10)?.parse().ok()?))(); // old

let property = try { string.get(5..10)?.parse().ok()? }; // new

Categories

  • Kind: clippy::style or clippy::complexity

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

More idiomatic via usage of the intended language feature instead of abusing closures.

Drawbacks

None.

Example

let nested_property: Option<C> = (|| Some(object.a?.b?.c?))();

Could be written as:

let nested_property: Option<C> = try { object.a?.b?.c? };

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsL-styleLint: Belongs in the style lint groupL-suggestionLint: Improving, adding or fixing lint suggestions

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions