Closed
Description
What it does
Uses of Pattern
(in methods like str.split()
, str.replace()
, str.trim_matches()
) where the pattern is a closure matching char
s:
str.split(|c: char| c == '\n' || c == 'X') // or
str.split(|c: char| matches!(c, '\n' | 'X'))
can be expressed more succinctly as:
str.split(['\n', 'X'])
and a single-char comparison can be simplified further.
Advantage
It makes the code much shorter, and the character set much easier to read.
They all have about the same performance, except a single-char pattern is much faster than the other forms.
Drawbacks
No response
Example
sentence.trim_end_matches(|c: char| c == '.' || c == '!' || c == '?')
Could be written as:
sentence.trim_end_matches(['.', '!', '?'])