Rust - std::convert::Into and std::convert::From

January 12, 2017    rust

I’ve been spending time recently learning the Rust Programming Language by writing a Riak Client using Riak’s Protocol Buffers API.

Through Ownership & Borrowing Rust enables safety that generally comes at the cost of flexibility. Through features like Traits Rust is able to give some flexibility back to the programmer.

Some traits I’ve started to use recently include std::convert::Into and std::convert::From.

When the Into trait is applied to a type, it allows it to consume itself to convert to another type.

The String type provides conversion into Vec<u8>:

fn is_hello<T: Into<Vec<u8>>>(s: T) {
   let bytes = b”hello”.to_vec();
   assert_eq!(bytes, s.into());
}

let s = “hello”.to_string(); is_hello(s);

One of the things I’ve been striving for while writing the Rust Riak Client has been clean interfaces where a Vec<u8> is ultimately needed under the hood, but I want to make it easy for the end-users to provide string types where applicable.

By using Into in a Generic one can make a very flexible interface to provide a Vec<u8>:

fn myfunc<T: Into<Vec<u8>>>(data: T) {
   // …
}
This function can now take String, &String, &str making the conversion of a string type to bytes (for the purposes of sending via TCP to Riak) a matter of function definition, which is super sleek.

I really enjoy writing code in Rust. I expect I’ll have a lot more write-ups to come as I discover things and learn better ways to do things I had already been doing.

If you’ve never checked out rust, try the Rust Playground!

Happy coding!