rustHow to convert a slice of bytes to a string in Rust?
To convert a slice of bytes to a string in Rust, you can use the std::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 = std::str::from_utf8(&bytes).unwrap();
Output example
hello
The code above does the following:
let bytes = [104, 101, 108, 108, 111];- creates a byte array containing the ASCII codes for the charactersh,e,l,l, ando.let string = std::str::from_utf8(&bytes).unwrap();- calls thestd::str::from_utf8function with the byte array as an argument, and assigns the result to thestringvariable. Theunwrapmethod is used to convert theResultinto a&str.
Helpful links
Related
- How to convert a Rust slice of u8 to u32?
- How to convert a Rust slice to a fixed array?
- How to convert a Rust slice of u8 to a string?
- How to split a Rust slice?
- How to push an element to a Rust slice?
- How to remove the last element of a Rust slice?
- How to iterate over a Rust slice with an index?
- How to remove elements from a Rust slice?
- How to reverse a Rust slice?
- How to calculate the sum of a Rust slice?
More of Rust
- How to match whitespace with a regex in Rust?
- Regex example to match multiline string in Rust?
- How to create a Rust regex from a string?
- How to use modifiers in a Rust regex?
- How to split a string by regex in Rust?
- How to use regex to match a double quote in Rust?
- How to compare two HashSets in Rust?
- How to insert an element into a Rust HashMap if it does not already exist?
- How to use Unicode in a regex in Rust?
- How to sort a Rust HashMap?
See more codes...