rustHow to convert Rust bytes to a string?
To convert Rust bytes to a string, you can use the str::from_utf8
function. This function takes a &[u8]
as an argument and returns a Result<&str, Utf8Error>
.
Example code
let bytes = b"Hello world!";
let string = str::from_utf8(bytes).unwrap();
println!("{}", string);
Output example
Hello world!
Code explanation
let bytes = b"Hello world!";
: This line creates a byte array containing the string "Hello world!".let string = str::from_utf8(bytes).unwrap();
: This line calls thestr::from_utf8
function with the byte array as an argument. Theunwrap
method is used to get the&str
from theResult<&str, Utf8Error>
returned by the function.println!("{}", string);
: This line prints the string to the console.
Helpful links
Related
More of Rust
- How to replace strings using Rust regex?
- How to use regex to match a group in Rust?
- How to use regex to match a double quote in Rust?
- How to parse JSON string in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to use a tuple as a key in a Rust HashMap?
- How to use non-capturing groups in Rust regex?
- How to get a capture group using Rust regex?
- How to perform matrix operations in Rust?
- How to get an entry from a HashSet in Rust?
See more codes...