Rust Reference ยท Strings and Text
Rust as_bytes, into_bytes and encode_utf8
Reference for Rust as_bytes, into_bytes, into_boxed_str, char::encode_utf8, len_utf8 and byte string literals: viewing and building the UTF-8 bytes of text.
Every str is a slice of bytes in UTF-8. as_bytes() shows you those bytes as a &[u8] without copying, and String::into_bytes() gives you the underlying Vec<u8> by consuming the string. For a single char, encode_utf8 writes its UTF-8 form into a buffer you provide and returns it as a &mut str.
Going the other way, from bytes back to text, needs validation: see from_utf8.
let bytes = "hi".as_bytes(); assert_eq!(bytes, &[104, 105]);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
fn str::as_bytes(&self) -> &[u8] fn String::into_bytes(self) -> Vec<u8> unsafe fn str::as_bytes_mut(&mut self) -> &mut [u8] fn char::encode_utf8(self, dst: &mut [u8]) -> &mut str fn char::len_utf8(self) -> usize fn char::encode_utf16(self, dst: &mut [u16]) -> &mut [u16] fn String::into_boxed_str(self) -> Box<str>
| Name | Description |
|---|---|
dst |
The buffer to write into. For UTF-8 use at least 4 bytes ([0u8; 4]); for UTF-16 at least 2 u16s. |
Returns: as_bytes returns a borrowed slice with the same lifetime as the string. into_bytes returns the owned Vec<u8>, reusing the allocation. encode_utf8 returns the written part of the buffer as a string slice.
Errors / panics / edge cases: encode_utf8 panics if the buffer is too small, which a 4-byte array can never be. as_bytes_mut is unsafe because writing invalid UTF-8 through it breaks the string's guarantee. The safe alternatives are make_ascii_uppercase and make_ascii_lowercase.
Usage notes
as_bytesis free. It reinterprets the pointer and length; there is no scan or copy.into_bytesis free too, and gives up theStringtype. Re-wrapping withString::from_utf8revalidates the bytes.- Bytes are not characters.
as_bytes()[i]is the i-th byte. For non-ASCII text one character spans two to four bytes (seechars). - Byte literals:
b'a'is au8, andb"abc"is a&[u8; 3]. Both are ASCII only (escapes likeb"\xFF"are allowed in byte strings). - ASCII helpers on
u8:is_ascii_digit,to_ascii_uppercaseand friends work on bytes directly and are a good fit for protocols and parsers. - Hex output:
{:02x}formats a byte as two hex digits;{:x?}prints a whole slice in hex. - Writing text to I/O takes bytes:
stdout.write_all(s.as_bytes()). Box<str>(frominto_boxed_str) drops the spare capacity, saving 8 bytes per string for long-lived read-only text.
Related
from_utf8,chars,bytes,CString,String,len- Lessons: Strings, Strings overview