-
Notifications
You must be signed in to change notification settings - Fork 1.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Complexity lint against some_string.as_bytes().len()
#13434
Comments
@rustbot claim |
I got bit recently by forgetting that I understand where folks are coming from on this, but still...I suspect there's two kinds of uses of Would it be possible to have the opposite lint as an opt-in and have it disable this lint? |
The category was discussed a fair bit on Zulip and a poll was created to ultimately decide, see the thread: https://rust-lang.zulipchat.com/#narrow/channel/257328-clippy/topic/FCP.3A.20needless_as_bytes If you want the opposite of this lint, you can disallow the use of disallowed-methods = [
{ path = "str::len", reason = "use <str>.as_bytes().len() instead" }
] I don't know if it's worth having an opt-in lint for something that |
Thank you! I was not aware of |
What it does
This lint would recommend changing instances of
some_string.as_bytes().len()
tosome_string.len()
.Explanation: When getting the length of a string,
str::len()
already returns the length in bytes. Converting a string to&[u8]
usingstr::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
Could be written as:
The text was updated successfully, but these errors were encountered: