Closed
Description
What it does
I stumbled upon cases when developers are not familiar enough with all the functions that come with standard libs, such as Option::filter()
. Instead, they program that functionality each time, which makes the code much more complex, error prone, and less readable.
Lint Name
filter
Category
style, complexity
Advantage
- Reduces complexity substantially.
- Improves code readability.
- Makes use of lib function instead of coding its functionality in each usage.
Drawbacks
None that I can think of.
Example
match s {
None => None,
Some(x) => {
if x.is_empty() {
None
} else {
Some(x)
}
}
}
Could be written as:
s.filter(|x| !x.is_empty())
Full example:
fn bad(s: Option<String>) -> Option<String> {
match s {
None => None,
Some(x) => {
if x.is_empty() {
None
} else {
Some(x)
}
}
}
}
fn good(s: Option<String>) -> Option<String> {
s.filter(|x| !x.is_empty())
}
fn main() {
assert_eq!(bad(None), None);
assert_eq!(bad(Some("".to_owned())), None);
assert_eq!(bad(Some("foo".to_owned())), Some("foo".to_owned()));
assert_eq!(good(None), None);
assert_eq!(good(Some("".to_owned())), None);
assert_eq!(good(Some("foo".to_owned())), Some("foo".to_owned()));
}