rust-lang / rust-lang/rust-clippy
Replace self-calling closures with try blocks (once stabilized)
Nobody has claimed this yet.
- 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::styleorclippy::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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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