rust-lang / rust-lang/rust-clippy

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

Open
#6,426 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint L-style L-suggestion
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

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? };

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Review Rust's try-blocks language-feature documentation and compare it with the self-calling closure examples in the issue. Determine whether try blocks are stabilized and whether Clippy can recognize this pattern safely. Done means the proposed style or complexity lint is implemented with coverage for the shown nested-optional and parsing examples.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.