rustHow do I convert a string to bytes in Rust?
To convert a string to bytes in Rust, you can use the as_bytes()
method. This method returns a &[u8]
which is a slice of bytes.
Example code
let my_string = "Hello World";
let my_bytes = my_string.as_bytes();
Output example
[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]
Code explanation
let my_string = "Hello World";
: This declares a variablemy_string
and assigns it the value of the string"Hello World"
.let my_bytes = my_string.as_bytes();
: This calls theas_bytes()
method on themy_string
variable, and assigns the result to themy_bytes
variable.
Helpful links
More of Rust
- How to replace a capture group using Rust regex?
- How to get an entry from a HashSet in Rust?
- How to create a HashSet from a Vec in Rust?
- How to match a string with regex in Rust?
- How to use regex to match a double quote in Rust?
- How to use an enum in a Rust HashMap?
- How to compare two Rust HashMaps?
- How to convert a Rust slice to a fixed array?
- How to convert a Rust HashMap to a BTreeMap?
- How to replace strings using Rust regex?
See more codes...