What can be bound to a slice?

What mechanism makes &Vec<T> bindable to &[T] (as in the following code)?

let v = vec![1,2,3];
let x: &[i32] = &v;

Put another way, is it possible to make the last line in the following sample, compile?

struct W(Vec<i32>);
let w = W(vec![1,2,3]);
let y: &[i32] = &w;

I'm expecting there to be some trait that is responsible for this, but I'm failing to find it.

You are quite right regarding this. There are the Deref and DerefMut traits which allow a type to be borrowed as another type, ie, by default borrowing T will always create &T or &mut T. However, as you have noted for Vec, it can be borrowed as &Vec<T> or as &[T]. This is because Vec has impls for Deref and for DerefMut.
This automatic "conversion", ie, deciding when to apply the Deref trait is known as deref coercion.

6 Likes

There is more information on coercions (including a list of places where the compiler allows them) here: Type coercions - The Rust Reference

5 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.