About iter method of array

In my understanding, we can call iter method on an Vec because Vec implements the Deref trait. But for primitive array how iter works? Does the compiler inject an implementation of Deref on it? Many thanks!

This might be of interest to you:

Quoting the documentation:

Arrays coerce to slices ( [T] ), so a slice method may be called on an array. Indeed, this provides most of the API for working with arrays.

So, for method resolution it's effectively the same as Deref, but internal implementation is different. In particular, you can't use array in places where you expect impl Deref<[T]>.

Did you mean [T;N] will coerce to [T]? But how compiler known that without any tips? like this

fn main() {

The coercion from &[T; N] to &[T] is hardcoded in the compiler.

Could you give me a reference? Which part of the source code ?

This is the Unsize adjustment:

It is created by coerce_unsized:


Aha, so it's the same that lets you convert &MyStruct into &dyn MyTrait.

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.