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_stringand assigns it the value of the string"Hello World".let my_bytes = my_string.as_bytes();: This calls theas_bytes()method on themy_stringvariable, and assigns the result to themy_bytesvariable.
Helpful links
More of Rust
- How to perform matrix operations in Rust?
- How to sort a Rust HashMap?
- How to convert a Rust slice of u8 to u32?
- How to convert Rust bytes to a struct?
- Yield example in Rust
- How to convert a u8 slice to a hex string in Rust?
- How to create a subslice from a Rust slice?
- How to extend struct from another struct in Rust
- How to add matrices in Rust?
- How to map with index in Rust
See more codes...