How to convert a vector of u8 to a string in Rust
What is a vector in Rust?
A vector in Rust is an array that can grow dynamically, allowing new elements to be added at runtime. It can store multiple values of the same type and is represented by the Vec<T> notation, where T denotes the vector type.
Vector of type u8
A vector of u8 is a data structure in Rust that represents a sequence of bytes. The u8 type in Rust represents an unsigned 8-bit integer that can hold values between 0 and 255. Therefore, a vector of u8 can store a sequence of bytes with values ranging from 0 to 255. Here's an example of how to create a vector of u8 in Rust:
// create a vector of u8 byteslet mut bytes: Vec<u8> = vec![72, 101, 108, 108, 111]; // represents "Hello" in ASCII
Converting to string
To convert a vector of u8 bytes to a string in Rust, we can use the String::from_utf8() method.
Example
fn main() {let my_vec: Vec<u8> = vec![72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]; // "Hello World" in ASCIIlet vec_to_string = String::from_utf8(my_vec).unwrap(); // Converting to stringprintln!("{}", vec_to_string); // Output: Hello World}
Explanation
Line 2: We create and initialize a vector
my_vecwith "Hello World" in ASCII using thevec!macro method.Line 3: We call the
String::from_utf8()method and passmy_vecas an argument. This method returns aResulttype, which we can unwrap to get the resultingstringand store it in thevec_to_stringvariable.Line 4: We print the
vec_to_string.
The method will return an error if the bytes vector contains invalid UTF-8 sequences. In the example above, we're using the unwrap() method to detect if there's an error. In the production stage, handling the error gracefully is usually better.
Free Resources