3 ms·
"str" and "String" guarantee UTF-8. To make a String from an array of bytes, call pub fn from_utf8(vec: Vec<u8, Global>) -> Result<String, FromUtf8Error>
by Animats 4y ago
"str" and "String" guarantee UTF-8. To make a String from an array of bytes, call
pub fn from_utf8(vec: Vec<u8, Global>) -> Result<String, FromUtf8Error>
which consumes the input Vec and returns it unmodified, if it's valid UTF-8,, or reports an error, if it's not. There are a number of related functions in this family. Such as
pub fn from_utf8_lossy(v: &[u8]) -> Cow<'_, str>
which takes in a slice of bytes and checks if it's a UTF-8 string. If it is, it returns the original str. Otherwise it makes a copy with any errors replaced with the Unicode error character.
Vec<u8> and array slices such as &[u8] are primitive containers - they can store any sequence of u8 values. String is more like an object with access methods.