Tianchi YU's Blog

INTO or AS (in the context of Rust Programming)?

Simple, but essential fact in this post.

To help you better understand the concept of ownership in Rust, it is a good example to learn.

As is known, String in Rust refers to a dynamically sized, UTF-8 encoded heap-allocated data type, and a byte in Rust refers to an 8-bit (unsigned) integer. How could we convert a string to bytes?

as_bytes: pub fn as_bytes(&self) -> &[u8]

You must hear about this method, which returns a byte slice of the String's contents.

Here is an example presenting its basic usage:

let s = String::from("hello");

assert_eq!(&[104, 101, 108, 108, 111], s.as_bytes());

What is the best of this function? It is we never grab the ownership of the String. So the following code works:

let s = String::from("hello");
let b = s.as_bytes();
assert_eq!(&[104, 101, 108, 108, 111], b);
println!("{}", s);
println!("{:?}",b);

Note: the inverse of this method is from_utf8, so we could use String::from_utf8(my_bytes.to_vec()).unwrap() to convert bytes to String.

into_bytes: pub fn into_bytes(self) -> Vec<u8, Global>

What happened with this method? It converts a String into a byte vector, which consumes the String so we don't need to copy its contents at all. It means the ownership of the String is taken by the byte vector and the variable of String is no longer valid.

The basic usage is:

let s = String::from("hello");
let bytes = s.into_bytes();

assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);

However, the following code would return an error of borrow of moved value.

let s = String::from("hello");
let bytes = s.into_bytes();

assert_eq!(&[104, 101, 108, 108, 111][..], &bytes[..]);

println!("{:?}", bytes);
println!("{}", s);

So, these two similar methods show us clearly how ownership works in Rust. AS keyword lets the priginal data type present AS another data type, but INTO keyword takes the contents(ownership) and converts original data type INTO another data type.

#rust