rustHow do I convert a string to a vector of u8 in Rust?
To convert a string to a vector of u8 in Rust, you can use the as_bytes()
method on a String
type. This will return a &[u8]
type, 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!");
: creates aString
type from the string literal"Hello world!"
let v: Vec<u8> = s.as_bytes().to_vec();
: creates aVec<u8>
type from the&[u8]
type returned by theas_bytes()
method on theString
type
Helpful links
More of Rust
- How to convert a Rust HashMap to a BTreeMap?
- How to use regex to match a double quote in Rust?
- How do I identify unused variables in Rust?
- How to get a capture group using Rust regex?
- How to use regex to match a group in Rust?
- How to calculate the inverse of a matrix in Rust?
- How to parse JSON string in Rust?
- How to implement PartialEq for a Rust HashMap?
- How to use a tuple as a key in a Rust HashMap?
- How to get the last element of a Rust slice?
See more codes...