]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/src/docs/suspicious_to_owned.txt
Rollup merge of #101189 - daxpedda:ready-into-inner, r=joshtriplett
[rust.git] / src / tools / clippy / src / docs / suspicious_to_owned.txt
1 ### What it does
2 Checks for the usage of `_.to_owned()`, on a `Cow<'_, _>`.
3
4 ### Why is this bad?
5 Calling `to_owned()` on a `Cow` creates a clone of the `Cow`
6 itself, without taking ownership of the `Cow` contents (i.e.
7 it's equivalent to calling `Cow::clone`).
8 The similarly named `into_owned` method, on the other hand,
9 clones the `Cow` contents, effectively turning any `Cow::Borrowed`
10 into a `Cow::Owned`.
11
12 Given the potential ambiguity, consider replacing `to_owned`
13 with `clone` for better readability or, if getting a `Cow::Owned`
14 was the original intent, using `into_owned` instead.
15
16 ### Example
17 ```
18 let s = "Hello world!";
19 let cow = Cow::Borrowed(s);
20
21 let data = cow.to_owned();
22 assert!(matches!(data, Cow::Borrowed(_)))
23 ```
24 Use instead:
25 ```
26 let s = "Hello world!";
27 let cow = Cow::Borrowed(s);
28
29 let data = cow.clone();
30 assert!(matches!(data, Cow::Borrowed(_)))
31 ```
32 or
33 ```
34 let s = "Hello world!";
35 let cow = Cow::Borrowed(s);
36
37 let data = cow.into_owned();
38 assert!(matches!(data, String))
39 ```