]> git.proxmox.com Git - rustc.git/blame - src/tools/clippy/src/docs/string_lit_as_bytes.txt
New upstream version 1.66.0+dfsg1
[rustc.git] / src / tools / clippy / src / docs / string_lit_as_bytes.txt
CommitLineData
f2b60f7d
FG
1### What it does
2Checks for the `as_bytes` method called on string literals
3that contain only ASCII characters.
4
5### Why is this bad?
6Byte string literals (e.g., `b"foo"`) can be used
7instead. They are shorter but less discoverable than `as_bytes()`.
8
9### Known problems
10`"str".as_bytes()` and the suggested replacement of `b"str"` are not
11equivalent because they have different types. The former is `&[u8]`
12while the latter is `&[u8; 3]`. That means in general they will have a
13different set of methods and different trait implementations.
14
15```
16fn f(v: Vec<u8>) {}
17
18f("...".as_bytes().to_owned()); // works
19f(b"...".to_owned()); // does not work, because arg is [u8; 3] not Vec<u8>
20
21fn g(r: impl std::io::Read) {}
22
23g("...".as_bytes()); // works
24g(b"..."); // does not work
25```
26
27The actual equivalent of `"str".as_bytes()` with the same type is not
28`b"str"` but `&b"str"[..]`, which is a great deal of punctuation and not
29more readable than a function call.
30
31### Example
32```
33let bstr = "a byte string".as_bytes();
34```
35
36Use instead:
37```
38let bstr = b"a byte string";
39```