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 convert Rust bytes to a vector of u8?
- How to write struct to json file in Rust
- How to extend struct from another struct in Rust
- How to convert the keys of a Rust HashMap to a vector?
- How to clear a Rust HashMap?
- How do I drop a variable in Rust?
- How to get all elements of a Rust slice except the last one?
- What is an enum variable in Rust?
- How to compare with null in Rust
- How to escape dots with regex in Rust?
See more codes...