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:
https://github.com/rust-lang/rust/issues/65798

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() {
    [1,2].iter();
}

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:

https://github.com/rust-lang/rust/blob/f4e4485a052857e5dd32ea29ceb7b1a8223e83cc/compiler/rustc_middle/src/ty/adjustment.rs#L27-L37

It is created by coerce_unsized:

https://github.com/rust-lang/rust/blob/41dc3942eb33e8e882b6e4782a9bd9d2b8970647/compiler/rustc_typeck/src/check/coercion.rs#L441

2 Likes

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.