How to convert a vector of bytes (Vec<u8>) to a string in Rust?
Hi everyone! I started learning Rust and ran into a problem when working with byte data. I have a byte vector `Vec` that I got, for example, when reading a file or from a network request. I need to convert this vector back to a regular `String` to display it on the screen or process it as text.
The problem is that I can't just write `my_vec.to_string()` or use `String::from()`. The compiler gives errors. Here's an example code that doesn't work for me:
```rust
fn main() {
let bytes: Vec = vec![72, 101, 108, 108, 111]; // "Hello" in ASCII
let text: String = bytes; // Error: expected String, found Vec
println!("{}", text);
}
```
I understand that bytes are just numbers, and a string is a sequence of characters in an encoding.
No answers yet.
Log in to leave an answer
Blogs