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 bytes
let 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 ASCII
let vec_to_string = String::from_utf8(my_vec).unwrap(); // Converting to string
println!("{}", vec_to_string); // Output: Hello World
}

Explanation

  • Line 2: We create and initialize a vector my_vec with "Hello World" in ASCII using the vec! macro method.

  • Line 3: We call the String::from_utf8() method and pass my_vec as an argument. This method returns a Result type, which we can unwrap to get the resulting string and store it in the vec_to_string variable.

  • 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

Copyright ©2025 Educative, Inc. All rights reserved