Why can I call the last method on a fixed-size array while this type doesn't implement that function?

Viewed 72

I have a fixed-size array I want to get the last element:

let array = [1, 2, 3];

According to the documentation page of the fixed-size array, there is no last method directly implemented for that type.

After a quick research, I have noticed the slice type implements the last method. All I have to do now is to find a way to convert my array to a slice. I can do that using the iter method:

let last = array.iter().last();

But I also have noted that I can omit the call to iter and get the exactly same behavior:

let last = array.last();

Why is this possible? How can the fixed-size array type call a method it doesn't implement? I have taken a look to all the traits implemented for that type and none of them have a last method.

While I was writing this question, I also noticed the iter function is not defined for the fixed-size array type. Is the documentation partial? Or am I bad at reading it?

1 Answers

This is a special case for the array-types, which coerce into slices of the same type automatically. The docs have (only) a small sentence about this:

Arrays coerce to slices ([T]), so a slice method may be called on an array.

I both cases the array is coerced into a slice, so you end up calling .iter() and .last() on an implicit slice, not on the array.

Related