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 aString
from the given string literal. -
let v: Vec<u8> = s.as_bytes().to_vec();
: This line calls theas_bytes()
method on theString
to 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 regex to match a double quote in Rust?
- How to get a capture group using Rust regex?
- How to use non-capturing groups in Rust regex?
- How to parse JSON string in Rust?
- How to use regex to match a group in Rust?
- How to use regex with bytes in Rust?
- How to replace all using regex in Rust?
- Hashshet example in Rust
- How to replace a capture group using Rust regex?
- How to replace all matches using Rust regex?
See more codes...