Skip to content

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

Closed
@LikeLakers2

Description

@LikeLakers2

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();

Metadata

Metadata

Assignees

Labels

A-lintArea: New lints

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions