How to understand array type's source code in std?

I am reading std code of 1.79.0-nightly version.
then I run into the library/core/src/array/mod.rs file.

#[stable(feature = "array_as_slice", since = "1.57.0")]
#[rustc_const_stable(feature = "array_as_slice", since = "1.57.0")]
pub const fn as_slice(&self) -> &[T] {
    self
}
#[stable(feature = "rust1", since = "1.0.0")]
impl<'a, T, const N: usize> IntoIterator for &'a [T; N] {
    type Item = &'a T;
    type IntoIter = Iter<'a, T>;

    fn into_iter(self) -> Iter<'a, T> {
        self.iter()
    }
}

I just can not understand above code. As for “as_slice", how can a self return value be convert to &[T] ? Also, in ”into_iter“ function, where does "iter() " function implemented?
Does both of them implement by compiler?
Does the feature = "array_as_slice" and #[stable(feature = "rust1", since = "1.0.0")] indicate that they are implement by compiler?

That's a type of coercion called deref coercion. Edit: It's actually also unsized coercion. Going from &Vec<T> to &[T] would be deref coercion. But what kind of coercion it actually is shouldn't be overly important; being aware what coercion is and where it happens should be sufficient in most cases.

That's another kind of coercion happening. &[T;N] can be unsized to &[T], which implements the iter method.

2 Likes

Thanks for you answer.
My initial goal was to find out where do 'iter()' implementation.
and I debug running into x.iter() as a digging, it do step into slice's iter().

        let x = &[1, 2, 4];
        let mut iterator = x.iter();

I has some knowledge of coercoin. But, how do you found or how can I found "&[T;N] can be unsized to &[T] ". I am total has no cue.

1 Like

Specifically, coercion semantics are documented in The Rust Reference book (see the links jofas provided).

In general, you have to know what to look for. Which can mean you once read the book cover-to-cover, or you picked it up along the way through casual conversation.

2 Likes