January 2018
Beginner to intermediate
454 pages
10h 8m
English
Arrays are fixed-size, but if we want to create a function that works with arrays of any size, we need to use another type: a slice.
A slice is a view into a contiguous sequence: it can be a view of the whole array, or a part of it. Slices are fat pointers, in addition to the pointer to the data, they contain a size. Here's a function that returns a reference to the first element of a slice:
fn first<T>(slice: &[T]) -> &T { &slice[0] }
Here, we use a generic type without bound since we don't use any operation on values of the T type. The &[T] parameter type is a slice of T. The return type is &T, which is a reference on values of the T type. The body of the function is &slice[0], which returns a reference to the first element of the ...
Read now
Unlock full access