Peter Lenkefi
Peter Lenkefi

Reputation: 1346

How does slice indexing work in Rust?

I wondered what slices were in Rust. As it turned out, it's just a struct with a data pointer and the size inside. I've looked at the source for indexing and I've found this:

impl<T> ops::Index<usize> for [T] {
    type Output = T;

    fn index(&self, index: usize) -> &T {
        // NB built-in indexing
        &(*self)[index]
    }
}

I'm not a Rust expert but &(*self) seems like a pointer for me and there is no pointer indexing in Rust as far as I know. So how does this indexing thing work? Is it just a compiler built-in thing?

Upvotes: 4

Views: 4677

Answers (1)

Lukas Kalbertodt
Lukas Kalbertodt

Reputation: 88536

Is it just a compiler built-in thing?

Yes. The source code comment also says that same. [T] is an unsized type and needs some extra rules anyway. For example, unsized types can't live on the stack (are pretty difficult to handle). But references to unsized types consist of a pointer and a size (specifically "something that completes the type").

Note, however, that the expression is evaluated like this: &((*self)[index]). This means that self (type &[T]) is dereferenced to be type [T] and then indexed. This returns a T, but we only want a reference to it, thus the &.

Upvotes: 4

Related Questions