rust/src/docs/or_fun_call.txt
relrelb f0e586c251 Suggest Entry::or_default for Entry::or_insert(Default::default())
Unlike past similar work done in #6228, expand the existing `or_fun_call`
lint to detect `or_insert` calls with a `T::new()` or `T::default()`
argument, much like currently done for `unwrap_or` calls. In that case,
suggest the use of `or_default`, which is more idiomatic.

Note that even with this change, `or_insert_with(T::default)` calls
aren't detected as candidates for `or_default()`, in the same manner
that currently `unwrap_or_else(T::default)` calls aren't detected as
candidates for `unwrap_or_default()`.

Also, as a nearby cleanup, change `KNOW_TYPES` from `static` to `const`,
since as far as I understand it's preferred (should Clippy have a lint
for that?).

Fixes #3812.
2022-09-04 23:43:17 +03:00

27 lines
No EOL
637 B
Text

### What it does
Checks for calls to `.or(foo(..))`, `.unwrap_or(foo(..))`,
`.or_insert(foo(..))` etc., and suggests to use `.or_else(|| foo(..))`,
`.unwrap_or_else(|| foo(..))`, `.unwrap_or_default()` or `.or_default()`
etc. instead.
### Why is this bad?
The function will always be called and potentially
allocate an object acting as the default.
### Known problems
If the function has side-effects, not calling it will
change the semantic of the program, but you shouldn't rely on that anyway.
### Example
```
foo.unwrap_or(String::new());
```
Use instead:
```
foo.unwrap_or_else(String::new);
// or
foo.unwrap_or_default();
```