Bernard
Bernard

Reputation: 5666

Why do arrays automatically convert themselves into slices?

In Rust, the slice type, [T], has many useful methods, such as .last(). However, equivalent methods are not present on the array type, [T; N], yet it is still possible to call those slice methods from an array object.

For example:

pub fn main() {
    let arr: [u32; 4] = [1, 2, 3, 4];
    let slice: &[u32] = &arr;

    // last() is a method of the (unsized) slice type, so this is fine
    println!("Slice len: {}", slice.last().unwrap());

    // This works, but how?
    println!("Array len: {}", arr.last().unwrap());
}

How does the array type automatically inherit the methods of the slice type? Is it possible to do so for a custom type?

I suspect that it is something to do with [T; N] implementing Borrow<[T]>, but that doesn't answer the question of why we don't need to write arr.borrow().last() instead.

(Note: I am trying to implement my own dynamically sized type that wraps an slice and a few other fields, and I would like to make the equivalent type wrapping an array inherit methods from my dynamically sized type.)

Upvotes: 1

Views: 50

Answers (0)

Related Questions