rustrust string as vec u8
A String in Rust is a UTF-8 encoded, growable array of bytes. It can be converted to a Vec<u8> using the as_bytes() method. This method returns a &[u8] which can be converted to a Vec<u8> using the to_vec() method.
Example code
let s = String::from("Hello world!");
let v: Vec<u8> = s.as_bytes().to_vec();
Output example
[72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33]
Code explanation
-
let s = String::from("Hello world!");: This line creates aStringfrom the given string literal. -
let v: Vec<u8> = s.as_bytes().to_vec();: This line calls theas_bytes()method on theStringto get a&[u8]slice, and then calls theto_vec()method on the slice to convert it to aVec<u8>.
Helpful links
More of Rust
- How to use binary regex in Rust?
- How to use regex to match a double quote in Rust?
- How to use negation in Rust regex?
- Regex example to match multiline string in Rust?
- How to use regex lookahead in Rust?
- How to ignore case in Rust regex?
- How to use regex captures in Rust?
- How to print a Rust HashMap?
- How to sort the keys in a Rust HashMap?
- Generator example in Rust
See more codes...