Rust - std :: string :: String as byte string (ie b "foo" or obsolete bytes! ("Foo"))

I see what

let s = String::from_str("hello");
let bytes = s.into_bytes();
assert_eq!(bytes, vec![104, 101, 108, 108, 111]);

      

but what i would like to do is

assert_eq!(s.something(), b"hello");

      

where .something()

is just a placeholder, it can be something(s)

or similar.

I am doing this so I can use lines with

fn foo(mut stream: BufferedStream<TcpStream>, str: String) {
   stream.write(str.something());
}

      

+3


source to share


2 answers


.something()

.something()

is called .as_slice()

. Typically, the word a &[T]

in rust is a slice, and the naming convention is cheap to borrow a type as another (in this case, from Vec<T>

) is .as_foo()

. In this new comparison, you are comparing &[u8]

rather than highlighting a new one Vec

for comparison. This should be much more efficient, and also more readable since no selection is required.



    assert_eq!(bytes.as_slice(), b"hello");

      

+5


source


First of all, you'd better write the following:

fn foo(mut stream: BufferedStream<TcpStream>, s: String) {
   stream.write(s.something());
}

      

like this:

fn foo(mut stream: BufferedStream<TcpStream>, s: &str) {
   stream.write(s.something());
}

      



Generally, try using slices ( &str

for String

) first, and if that doesn't work due to ownership, use String

.

Secondly, the method you are looking for is called as_bytes()

:

fn foo(mut stream: BufferedStream<TcpStream>, s: &str) {
   stream.write(s.as_bytes());
}

      

Don't need to convert String

to Vec<u8>

.

+2


source







All Articles