rustHow to convert a Rust byte slice to a str?
To convert a Rust byte slice to a str, you can use the str::from_utf8 function. This function takes a byte slice and returns a Result<&str, Utf8Error>.
Example code
let bytes = b"Hello world!";
let s = str::from_utf8(bytes).unwrap();
println!("{}", s);
Output example
Hello world!
Code explanation
let bytes = b"Hello world!";: This creates a byte slice containing the string "Hello world!".let s = str::from_utf8(bytes).unwrap();: This calls thestr::from_utf8function, passing in the byte slicebytes. Theunwrapmethod is used to get the&strfrom theResultreturned by the function.println!("{}", s);: This prints the&strto the console.
Helpful links
Related
- How to convert a Rust slice of u8 to u32?
- How to calculate the sum of a Rust slice?
- How to split a Rust slice?
- How to fill a Rust slice with a specific value?
- How to convert a Rust slice of u8 to a string?
- How to check for equality between Rust slices?
- How to iterate over a Rust slice with an index?
- How to shift elements in a Rust slice?
- How to sort a Rust slice by key?
- How to create a subslice from a Rust slice?
More of Rust
- How to replace a capture group using Rust regex?
- Regex example to match multiline string in Rust?
- How to match the end of a line in a Rust regex?
- How to use regex captures in Rust?
- How to use regex to match a group in Rust?
- How to find the first match in a Rust regex?
- How to convert a Rust slice of u8 to u32?
- How to use regex to match a double quote in Rust?
- How to convert struct to protobuf in Rust
- How to perform matrix operations in Rust?
See more codes...