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 of u8 to u32?
- How to calculate the sum of a Rust slice?
- How to create a subslice from a Rust slice?
- How to get the first element of a slice in Rust?
- How to convert a Rust slice to a fixed array?
- How to push an element to a Rust slice?
- How to get the last element of a Rust slice?
- How to convert a slice of bytes to a string in Rust?
- How to convert a u8 slice to a hex string in Rust?
More of Rust
- How to use non-capturing groups in Rust regex?
- How to get a capture group using Rust regex?
- How to replace a capture group using Rust regex?
- How to match all using regex in Rust?
- How to remove an element from a Rust HashMap if a condition is met?
- How to use regex lookahead in Rust?
- Example of yield_now in Rust?
- How to implement a generator trait in Rust?
- How to replace strings using Rust regex?
- How to find the first match in a Rust regex?
See more codes...