Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rust - std::string::String as a byte string (i.e. b"foo" or deprecated bytes!("foo"))

Tags:

rust

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());
}
like image 980
Victory Avatar asked Dec 15 '22 18:12

Victory


1 Answers

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");
like image 68
McPherrinM Avatar answered Dec 19 '22 10:12

McPherrinM