rustrust string as bytes
A Rust String can be converted to a Vec<u8> of bytes using the as_bytes() method. This method returns a &[u8] slice, which can be converted to a Vec<u8> using the to_vec() method.
Example
let my_string = String::from("Hello World!");
let bytes = my_string.as_bytes().to_vec();
Output example
[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]
Code explanation
my_string: aStringcontaining the text "Hello World!"as_bytes(): a method that returns a&[u8]slice of the bytes of theStringto_vec(): a method that converts a&[u8]slice to aVec<u8>
Helpful links
More of Rust
- How to use regex to match a double quote in Rust?
- How to create a HashMap of structs in Rust?
- How to replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to modify an existing entry in a Rust HashMap?
- How do I identify unused variables in Rust?
- How to use negation in Rust regex?
- Regex example to match multiline string in Rust?
- How to use a Rust HashMap in a struct?
- How do I use a variable number of arguments in Rust?
See more codes...