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 iterate over a Rust slice with an index?
- Does Rust perform bounds checking on slices?
- How to fill a Rust slice with a specific value?
- How to create a Rust slice with a specific size?
- How to convert a Rust slice of u8 to a string?
- How to convert a Rust slice of u8 to u32?
- How to swap elements in a Rust slice?
- How to reverse a Rust slice?
- How to map a Rust slice?
- How to push an element to a Rust slice?
More of Rust
- How to match the end of a line in a Rust regex?
- How to add an entry to a Rust HashMap?
- How to use regex captures in Rust?
- How to use binary regex in Rust?
- How to use named capture groups in Rust regex?
- Regex example to match multiline string in Rust?
- How to replace a capture group using Rust regex?
- How to use captures_iter with regex in Rust?
- How to make regex case insensitive in Rust?
- How to use regex with bytes in Rust?
See more codes...