rust-lang / rust-clippy

A bunch of lints to catch common mistakes and improve your Rust code. Book: https://doc.rust-lang.org/clippy/
https://rust-lang.github.io/rust-clippy/
Other
11.44k stars 1.54k forks source link

Complexity lint against `some_string.as_bytes().len()` #13434

Closed LikeLakers2 closed 1 week ago

LikeLakers2 commented 1 month ago

What it does

This lint would recommend changing instances of some_string.as_bytes().len() to some_string.len().

Explanation: When getting the length of a string, str::len() already returns the length in bytes. Converting a string to &[u8] using str::as_bytes(), and then getting the length of that, introduces unnecessary complexity where none is needed.

Advantage

Less complex-looking code, while still functioning the same.

Drawbacks

Applying this lint may make it less obvious that the length will be in bytes - because our intuition for getting a string's length is that it will be the number of characters. Yes, the rust documentation addresses this, but it's still quite easy to forget - especially for us english speakers, who probably only expect to deal with ASCII (which is only ever one byte in length).

Example

let string_len_in_bytes = some_string.as_bytes().len();

Could be written as:

let string_len_in_bytes = some_string.len();
samueltardieu commented 1 month ago

@rustbot claim