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
- Generator example in Rust
- How to replace a capture group using Rust regex?
- How to match a URL with a regex in Rust?
- How to use binary regex in Rust?
- How to use regex lookahead in Rust?
- How to make regex case insensitive in Rust?
- Regex example to match multiline string in Rust?
- How to use regex to match a double quote in Rust?
- Yield example in Rust
- How to use a tuple as a key in a Rust HashMap?
See more codes...