RS.CLIPPY.SLICED_STRING_AS_BYTES

Slicing a string and immediately calling as_bytes is less efficient and can lead to panics

This checker is a Clippy lint created by The Rust Project Contributors. The documentation shown here is a copy of the original documentation for: sliced_string_as_bytes. Copyright ©2025 The Rust Team. All rights reserved.

What it does

Checks for string slices immediately followed by as_bytes.

Why is this bad?

It involves doing an unnecessary UTF-8 alignment check which is less efficient, and can cause a panic.

Known problems

In some cases, the UTF-8 validation and potential panic from string slicing may be required for the code's correctness. If you need to ensure the slice boundaries fall on valid UTF-8 character boundaries, the original form (s[1..5].as_bytes()) should be preferred.

Example

let s = "Lorem ipsum";
s[1..5].as_bytes();

Use instead:

let s = "Lorem ipsum";
&s.as_bytes()[1..5];