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 calculate the sum of a Rust slice?
- How to convert a slice into an iter in Rust?
- How to convert a u8 slice to a hex string in Rust?
- How to push an element to a Rust slice?
- How to extend a Rust slice?
- How to check for equality between Rust slices?
- How to cast a Rust slice?
- What are the characters in a Rust slice?
- How to convert a slice of bytes to a string in Rust?
More of Rust
- How to parse a file with Rust regex?
- How to get a capture group using Rust regex?
- How to split a string with Rust regex?
- How to use non-capturing groups in Rust regex?
- How to use an enum in a Rust HashMap?
- How to replace a capture group using Rust regex?
- How to replace all matches using Rust regex?
- How to use regex lookahead in Rust?
- How to match the end of a line in a Rust regex?
- How to get all matches from a Rust regex?
See more codes...