Need help with Understanding Type Conversions in Rust

Hello, I am a beginner to Rust and was confused on how Rust handles typings.

I have a hexadecimal key which I have been trying to use the Rc4 crate to create an instance of Rc4 by using
Rc4::new(hex::decode(KEY).into())

Since Rc4 expects a byte sequence and hex::decode returns Vec, I have been trying to convert the latter type to the former using into() but could not figure out the reason for failure.

From my understanding of types, Vec is a String and byte sequence is a &str, so I thought into() would work here.

You will generally receive better quality help much faster when you post runnable code the illustrates the problem and the exact error message. The Rust Playground is helpful for that.

First of all, assuming hex::decode is this, it returns a Result<Vec, Error>, rather than just a Vec.

Second of all, if you use Rc4::new_from_slice, you can just pass a &decoded, thanks to &Vec -> &[T] coercion.

1 Like

A String is akin to a Vec<u8>, but with the invariant that the (initiated) bytes are valid UTF8. The String owns the bytes and it's growable.

A &str is a poniter to some string data - some contiguous bytes with the same UTF8 invariant. It doesn't own the bytes. It points to borrowed data, or static data (or leaked data etc).

Not all byte sequences are directly convertible to these string types as due to the UTF8 invariants.

Here's more about these types.

2 Likes