Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an ascii string literal to &[u8] in Rust?

Tags:

How do you convert an ascii string literal (say, "123 458") into a &[u8] slice in rust? Rust has 6? 7? string types, and there is almost no uniformity in what you call to convert between them.

I'm expecting it to be something along the lines of:

let array:&[u8] = Ascii("123 456").into_bytes().as_slice().givemetheeffingbufferalready() as &[u8]; 

Please take it on faith that I actually need to do this; I am writing test cases for some file parser code.

like image 753
Andrew Wagner Avatar asked Nov 28 '14 20:11

Andrew Wagner


People also ask

How do I convert ASCII to string?

To convert ASCII to string, use the toString() method. Using this method will return the associated character.

How do I convert ASCII characters?

C. C++ code: Here int() is used to convert a character to its ASCII value.

Is string an ASCII?

If text is being stored in a computer, it is usually stored as a string (a series of ASCII characters, each one of which is stored as one byte). The formatting characters such as space, carriage return and line feed may be included in the string.


1 Answers

After much digging through other related answers, and getting corrected by the nightly version of the compiler, I found out it is trivial; you just add a 'b' to your literal:

let array:&[u8] = b"123 456"; 
like image 158
Andrew Wagner Avatar answered Sep 17 '22 18:09

Andrew Wagner