]> git.lizzy.rs Git - rust.git/blob - src/docs/string_lit_as_bytes.txt
[Arithmetic] Consider literals
[rust.git] / src / docs / string_lit_as_bytes.txt
1 ### What it does
2 Checks for the `as_bytes` method called on string literals
3 that contain only ASCII characters.
4
5 ### Why is this bad?
6 Byte string literals (e.g., `b"foo"`) can be used
7 instead. 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
11 equivalent because they have different types. The former is `&[u8]`
12 while the latter is `&[u8; 3]`. That means in general they will have a
13 different set of methods and different trait implementations.
14
15 ```
16 fn f(v: Vec<u8>) {}
17
18 f("...".as_bytes().to_owned()); // works
19 f(b"...".to_owned()); // does not work, because arg is [u8; 3] not Vec<u8>
20
21 fn g(r: impl std::io::Read) {}
22
23 g("...".as_bytes()); // works
24 g(b"..."); // does not work
25 ```
26
27 The 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
29 more readable than a function call.
30
31 ### Example
32 ```
33 let bstr = "a byte string".as_bytes();
34 ```
35
36 Use instead:
37 ```
38 let bstr = b"a byte string";
39 ```