Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a str to a &[u8]

Tags:

string

slice

rust

This seems trivial, but I cannot find a way to do it.

For example,

fn f(s: &[u8]) {}  pub fn main() {     let x = "a";     f(x) } 

Fails to compile with:

error: mismatched types:  expected `&[u8]`,     found `&str` (expected slice,     found str) [E0308] 

documentation, however, states that:

The actual representation of strs have direct mappings to slices: &str is the same as &[u8].

like image 860
ynimous Avatar asked Jul 08 '15 10:07

ynimous


People also ask

What converts a string to a number?

You convert a string to a number by calling the Parse or TryParse method found on numeric types ( int , long , double , and so on), or by using methods in the System. Convert class. It's slightly more efficient and straightforward to call a TryParse method (for example, int.

How do you convert string to in Python?

To convert an integer to string in Python, use the str() function. This function takes any data type and converts it into a string, including integers. Use the syntax print(str(INT)) to return the int as a str , or string.

How do I convert a string to an int in C++?

One effective way to convert a string object into a numeral int is to use the stoi() function. This method is commonly used for newer versions of C++, with is being introduced with C++11. It takes as input a string value and returns as output the integer version of it.


1 Answers

You can use the as_bytes method:

fn f(s: &[u8]) {}  pub fn main() {     let x = "a";     f(x.as_bytes()) } 

or, in your specific example, you could use a byte literal:

let x = b"a"; f(x) 
like image 159
fjh Avatar answered Oct 13 '22 05:10

fjh