Avatar ·

How to convert between String, &str, Vec<u8> and &[u8] in Rust?

Hello everyone! I recently started learning Rust and I keep getting confused with conversions between strings and byte arrays. The problem arises because Rust has different types for strings: String, &str, and for bytes — Vec<u8> and &[u8].

\n\n

For example, I'm writing a simple program that reads a file, processes strings, and outputs the result. But I keep getting compilation errors because I can't figure out how to properly convert one type to another.

\n\n
use std::fs;\n\nfn main() {\n    let data: Vec<u8> = fs::read("example.txt").unwrap();\n    // How to convert Vec<u8> to String?\n    let text: String = ???;\n    \n    // Then I need to pass part of the string to a function that takes &