-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Closed
Labels
A-lintArea: New lintsArea: New lintsL-styleLint: Belongs in the style lint groupLint: Belongs in the style lint groupT-middleType: Probably requires verifiying typesType: Probably requires verifiying typesgood first issueThese issues are a good way to get started with ClippyThese issues are a good way to get started with Clippy
Description
What it does
Detect functions that end with Option::and_then
or Result::and_then
and suggest using a question mark instead.
Categories
- Kind: style, maybe pedantic
It is simpler and more idiomatic.
Drawbacks
None.
Example
fn test(opt: Option<i32>) -> Option<i32> {
opt.and_then(|n| {
if n > 1 {
Some(n + 1)
} else {
None
}
})
}
Could be written as:
fn test(opt: Option<i32>) -> Option<i32> {
let n = opt?;
if n > 1 {
Some(n + 1)
} else {
None
}
}
The and_then
call should be the very last expression of the function (not inside an if
block, for example).
More Questionable Cases
Single expression lambda (no block)
fn test(opt: Option<i32>) -> Option<i32> {
opt.and_then(|n| foo(n))
}
At the end of a call chain
fn foo() -> Option<i32> {
vec![1, 2, 3]
.iter()
.last()
.and_then(|n| {
// ...
})
}
Personally I think those cases should still be linted. Maybe it can be configurable.
sbdchd
Metadata
Metadata
Assignees
Labels
A-lintArea: New lintsArea: New lintsL-styleLint: Belongs in the style lint groupLint: Belongs in the style lint groupT-middleType: Probably requires verifiying typesType: Probably requires verifiying typesgood first issueThese issues are a good way to get started with ClippyThese issues are a good way to get started with Clippy