Rust bytes and String
In Rust a byte
refers to 8 bit unsigned integer.
In rust we can represent a byte by u8
A string can also be considered as a sequence of bytes. To convert a String
to sequence of bytes we can do as below
Output
To do the inverse, that is get a String
from sequence of bytes we can use String::from_utf8
. This returns a Result<String, FromUtf8Error>
.
Output
Curiously, I asked around in Rust’s discord why doesn’t String::from_utf8
take an array and only a Vector. Responses I got were
- String wraps a
Vec<u8>
so it will have to be converted toVec<>
either way. - Hence, we would need a heap allocation anyways to create a
String
. So if we take in aVec
we could just take the ownership of thatVec
.
Updated on