I see that
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 have
assert_eq!(s.something(), b"hello");
where .something()
is just a placeholder, it might be something(s)
or similar.
I am doing this so i can use strings with
fn foo(mut stream: BufferedStream<TcpStream>, str: String) {
stream.write(str.something());
}
The .something()
you want is called .as_slice()
. Generally the word for a &[T]
in rust is a slice, and the naming convention to cheaply borrow a type as another (in this case, from a Vec<T>
) is .as_foo()
. In this new comparison, you are comparing &[u8]
, instead of allocating a new Vec
to compare. This should be much more efficient as well as more readable, since no allocation is needed.
assert_eq!(bytes.as_slice(), b"hello");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With