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 shift elements in a Rust slice?
- Does Rust perform bounds checking on slices?
- How to map a Rust slice?
- How to split a Rust slice?
- How to convert a Rust slice to a fixed array?
- How to fill a Rust slice with a specific value?
- How to iterate over a Rust slice with an index?
- How to create a Rust slice with a specific size?
More of Rust
- How to replace strings using Rust regex?
- How to match whitespace with a regex in Rust?
- How to use non-capturing groups in Rust regex?
- How to declare a constant Rust HashMap?
- Bitwise operator example in Rust
- Regex example to match multiline string in Rust?
- How to match a URL with a regex in Rust?
- How to use regex lookbehind in Rust?
- How to replace a capture group using Rust regex?
- How to use regex lookahead in Rust?
See more codes...