Skip to content

String::as_bytes

String methods · Strings

Level: reference · for working programmers

One line: Borrows the String's UTF-8 bytes as &[u8] — free, and identical to str::as_bytes.

pub const fn as_bytes(&self) -> &[u8]

Stable since 1.0.0. Usable in a const context.

Same method, reached through the same deref. It is listed on String because the inherent version is const, and because it is the one people look for when they have an owned string.

Borrowed, so the String must outlive the slice and cannot be mutated meanwhile. For an owned Vec<u8> without a copy, use into_bytes.

s.as_bytes().len() is len, and indexing gives bytes, not characters.

Example

string_as_bytes.rs in full — pasted here by tools/run_examples.py from the file CI compiles and runs.

fn main() {
    let s = String::from("héllo");
    println!("{:?}", s.as_bytes());
    println!("{} bytes, {} chars", s.as_bytes().len(), s.chars().count());

    // Identical to the str method, reached by deref.
    println!("{}", s.as_bytes() == s.as_str().as_bytes());

    // Borrowed: the String is still there afterwards.
    let bytes = s.as_bytes();
    println!("first {:?}, and s is still {:?}", bytes.first(), s);

    // The owned version, which consumes the String and copies nothing.
    let owned = String::from("héllo");
    let v: Vec<u8> = owned.into_bytes();
    println!("{v:?}");

    // Writing bytes out is the usual reason.
    println!("{}", String::from("GET /").as_bytes().starts_with(b"GET"));
}

Verified output of string_as_bytes.rs — regenerated by tools/run_examples.py, never hand-typed.

[104, 195, 169, 108, 108, 111]
6 bytes, 5 chars
true
first Some(104), and s is still "héllo"
[104, 195, 169, 108, 108, 111]
true

See also

String::as_bytes in the standard library ↗

Po polsku

Podglądanie bajtów nic nie kosztuje: as_bytes zwraca &[u8] wskazujący prosto w bufor String — bez kopiowania i bez alokacji, a że wariant na String jest const, wolno go wywołać także w kontekście stałej. Zwrócony wycinek jest pożyczony, więc dopóki żyje, łańcucha znaków nie da się zmienić; gdy potrzebny jest własny Vec<u8>, into_bytes oddaje ten sam bufor również bez kopii, tyle że konsumując String. Najważniejsze jest tu nie pomylić poziomów: w wyniku przykładu "héllo" to sześć bajtów i pięć znaków, a bajty 195 i 169 to dwie połówki jednego é — polskie ą, ę czy ł zachowują się identycznie, więc indeksowanie wyniku as_bytes() daje bajty, nigdy znaki.

Szukaj po polsku: bajty łańcucha znaków · UTF-8 a indeksowanie znaków · rust String as_bytes vs into_bytes · rust get &[u8] from String