9951 explained code solutions for 126 technologies


rustHow to convert a Rust byte slice to a string?


To convert a Rust byte slice to a string, you can use the std::str::from_utf8 function. This function takes a byte slice and returns a Result<&str, Utf8Error>.

Example code

let bytes = b"Hello world!";
let string = std::str::from_utf8(bytes).unwrap();

Output example

Hello world!

Code explanation

  • let bytes = b"Hello world!";: This creates a byte slice containing the bytes of the string "Hello world!".
  • let string = std::str::from_utf8(bytes).unwrap();: This calls the std::str::from_utf8 function, passing in the byte slice bytes. The unwrap method is used to get the &str from the Result returned by the function.

Helpful links

Edit this code on GitHub