Reputation: 1346
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
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