String::into_bytes¶
Level: reference · for working programmers
One line: Consumes the String and returns its Vec<u8> — no copy, no validation, the same allocation relabelled.
Stable since 1.0.0. Usable in a const context.
A String is a Vec<u8> plus a UTF-8 guarantee. This drops the guarantee and hands the Vec over, which costs nothing: the pointer, length and capacity are moved across unchanged.
The trip back through String::from_utf8 costs one validating scan, and returns your Vec in the error if it fails — so a round trip is safe and cheap.
Use it when an API wants owned bytes: writing to a channel that takes Vec<u8>, or building a byte buffer that is not all text. When borrowing is enough, as_bytes is free too and keeps the String.
Example¶
string_into_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");
let cap = s.capacity();
let v = s.into_bytes();
println!("{v:?}");
println!("capacity carried across: {}", v.capacity() == cap);
// The round trip: one scan out, nothing copied either way.
let back = String::from_utf8(v).unwrap();
println!("{back:?}");
// The Vec can now hold anything, valid UTF-8 or not.
let mut bytes = String::from("hi").into_bytes();
bytes.push(0xff);
println!("{:?}", String::from_utf8(bytes.clone()).is_err());
println!("{:?}", String::from_utf8_lossy(&bytes));
// Borrowing instead, when the String should survive.
let keep = String::from("hi");
println!("{:?} and {keep:?}", keep.as_bytes());
}
Verified output of string_into_bytes.rs — regenerated by tools/run_examples.py, never hand-typed.
See also¶
String::from_utf8— the checked trip backString::as_bytes— borrowing instead of consumingString::into_boxed_str— keeping the UTF-8 guarantee but dropping capacitystr::into_boxed_bytes— the same move from aBox<str>
String::into_bytes in the standard library ↗
Po polsku¶
into_bytes pokazuje, czym String jest naprawdę: wektorem bajtów Vec<u8> z doklejoną gwarancją poprawnego UTF-8, a ta metoda tę gwarancję zdejmuje i oddaje sam wektor. Pochłania przy tym łańcuch znaków (consumes the String) — przejmuje własność i zwraca ten sam blok pamięci pod nową etykietą, bez kopiowania: wskaźnik, długość i pojemność (capacity) przechodzą nietknięte, co przykład na tej stronie potwierdza wierszem capacity carried across: true. Polskiego czytelnika zwykle zaskakuje tu arytmetyka: "héllo" to pięć znaków, ale sześć bajtów ([104, 195, 169, 108, 108, 111]), bo é zajmuje dwa — dokładnie tak samo jak ą, ę czy ł. Jeśli łańcuch ma przeżyć operację, sięgnij po as_bytes, które tylko pożycza; droga powrotna to String::from_utf8, kosztująca jeden przebieg sprawdzający i oddająca wektor z powrotem wewnątrz błędu, gdy bajty przestały być poprawnym UTF-8.
Szukaj po polsku: wektor bajtów · kodowanie UTF-8 · polskie znaki diakrytyczne a bajty · rust String into_bytes · rust String from_utf8