rustHow to convert a Rust slice of u8 to a string?
To convert a Rust slice of u8 to a string, you can use the str::from_utf8
function. This function takes a slice of bytes and returns a Result<&str, Utf8Error>
.
Example code
let bytes = [104, 101, 108, 108, 111];
let string = str::from_utf8(&bytes).unwrap();
Output example
hello
The code above does the following:
let bytes = [104, 101, 108, 108, 111];
- creates a slice of byteslet string = str::from_utf8(&bytes).unwrap();
- calls thestr::from_utf8
function with the&bytes
slice as an argument, and then unwraps theResult
to get the&str
Helpful links
- str::from_utf8 - official documentation for the
str::from_utf8
function
Related
- How to convert a Rust slice to a fixed array?
- How to convert a u8 slice to a hex string in Rust?
- How to get the last element of a Rust slice?
- How to convert a slice to a hex string in Rust?
- How to get the first element of a slice in Rust?
- How to push an element to a Rust slice?
- How to convert a Rust slice of u8 to u32?
- How to convert a Rust slice to a tuple?
- How to calculate the sum of a Rust slice?
More of Rust
- How to match the end of a line in a Rust regex?
- How to calculate the inverse of a matrix in Rust?
- How to use a HashBrown with a Rust HashMap?
- How to replace all using regex in Rust?
- How to use Unicode in a regex in Rust?
- How to replace a capture group using Rust regex?
- How to get a capture group using Rust regex?
- How to replace all matches using Rust regex?
- How to use 'or' in Rust regex?
- How to find the first match in a Rust regex?
See more codes...