I recognized you can use &Vec alsmost everywhere where a &[u8] is needed. For testing, I wrote this code:
fn main() {
let a = vec![9_u8, 1, 2];
let b: &[u8] = &a;
let c: &Vec<u8> = &a;
if b == c {
println!("test1");
}
assert_same_type(b, c);
}
fn assert_same_type<T: ?Sized>(_: &T, _: &T) {
println!{"test2"};
}
"test1" and "test2" are printed without any trouble. Are &[u8] and &Vec the same internally or is it just converted (like &String to &str)? I thought it could not be the same, because &[u8] is a slice of an array and &Vec of an Vector. But the test looks like I was wrong.
They are converted. Vec<u8> is a heap-allocated buffer, which is represented in memory as a triple (pointer, capacity, length). &Vec<u8> is a single pointer to that data. &[u8] is a borrowed slice. It consists only of (pointer, length). As you can see, all of those types have different memory representation.
Your test fails because the compiler automatically tries to coerce differing types to a single common type. This also happens for equality. The expression a == b really desugars to PartialEq::eq(&a, &b),where the trait resolution and type coercion are again applied.
The types which are defined differently are basically never the same, unless the names contain differing type aliases.
You can also see that you can't pass foo: &[u8] into a function fn bar(_: &Vec<u8>). The compiler will complain abou type mismatch.
The test does not fail unless one inverts the order b, c though. I think that's because of what the previous comment highlights: the vec is coerced since one is basically using &[u8]; and the reverse conversion can not happen.
Fail as in "doesn't provide the expected outcome", which in this case is a compiler error. Also, the order of operands in a == b doesn't matter in this case, since the coercion will be applied anyway. The order matters when the arguments aren't coercible, which is the common case, but not in this example.
A slice ([T]) can be a contiguous sequence of T from anywhere, not just an array. When you coerce &Vec<T> to &[T], the slice is the memory that the Vec<_> manages. The relationship between str and String is the same as [T] and Vec<T>.