Why can &Arc<Vec<T>> be assigned to a shared slice?

It just seems as if Index::index is called implicitly.

let arc = &Arc::new(vec![1, 2, 3]);
let mut slice: &[i32] = arc;
slice = arc.index(..);
slice = &arc[..];

This happens because both Arc and Vec implement Deref, so deref coercion applies. In particular &Arc<Vec<T>> can be implicitly be converted to &Vec<T> (because Arc implements Deref) and then &Vec<T> can be implicitly converted to &[T] (again because Vec implements Deref). This chapter of the book should explain it well.

Calling index on the Arc actually ends up calling the implementation for Vec (again because Arc implements Deref), and the implementation of Index for Vec when given .. is the same as its implementation of Deref .

3 Likes

Thanks a lot. I mistakenly believed that this would only happen when a method of the dereffed type is called explicitly, because this would not happen for those types which haven't implemented Deref.

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.