Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a string into a vector of bytes in rust?

That might be the dumbest Rustlang question ever but I promise I tried my best to find the answer in the documentation or any other place on the web.

I can convert a string to a vector of bytes like this:

let bar = bytes!("some string"); 

Unfortunately I can't do it this way

let foo = "some string"; let bar = bytes!(foo); 

Because bytes! expects a string literal.

But then, how do I get my foo converted into a vector of bytes?

like image 437
Christoph Avatar asked May 24 '14 23:05

Christoph


People also ask

How do you convert strings to bytes like objects?

The bytes() method is an inbuilt function that can be used to convert objects to byte objects. The bytes take in an object (a string in our case), the required encoding method, and convert it into a byte object. The bytes() method accepts a third argument on how to handle errors.

How do you convert a string to a number in Rust?

To convert a string to an integer in Rust, use parse() function. The parse function needs to know what type, which can be specified on the left-side of assignment like so: let str = "123"; let num: i32 = str. parse().


2 Answers

(&str).as_bytes gives you a view of a string as a &[u8] byte slice (that can be called on String since that derefs to str, and there's also String.into_bytes will consume a String to give you a Vec<u8>.

Use the .as_bytes version if you don't need ownership of the bytes.

fn main() {     let string = "foo";     println!("{:?}", string.as_bytes()); // prints [102, 111, 111] } 

BTW, The naming conventions for conversion functions are helpful in situations like these, because they allow you to know approximately what name you might be looking for.

like image 125
huon Avatar answered Sep 20 '22 19:09

huon


 `let v1: Vec<u8> = string.encode_to_vec();`  `let v2: &[u8]   = string.as_bytes();` 

two work difference, in some of library use ownership of bytes !! if you use as_bytes() see compiler error: must be static.

for example: tokio_uring::fs::File::write_at() get a ownership of bytes !!

but if you need borrowing , use as_bytes()

like image 23
Danyal Mh Avatar answered Sep 22 '22 19:09

Danyal Mh