Arrays and Slices

An array is a collection of objects of the same type T, stored in contiguous
memory. Arrays are created using brackets [], and their size, which is known
at compile time, is part of their type signature [T; size].

Slices are similar to arrays, but their size is not known at compile time.
Instead, a slice is a two-word object, the first word is a pointer to the data,
and the second word is the length of the slice. The word size is the same as
usize, determined by the processor architecture eg 64 bits on an x86-64.
Slices can be used to borrow a section of an array, and have the type signature
&[T].

  1. use std::mem;
  2. // This function borrows a slice
  3. fn analyze_slice(slice: &[i32]) {
  4. println!("first element of the slice: {}", slice[0]);
  5. println!("the slice has {} elements", slice.len());
  6. }
  7. fn main() {
  8. // Fixed-size array (type signature is superfluous)
  9. let xs: [i32; 5] = [1, 2, 3, 4, 5];
  10. // All elements can be initialized to the same value
  11. let ys: [i32; 500] = [0; 500];
  12. // Indexing starts at 0
  13. println!("first element of the array: {}", xs[0]);
  14. println!("second element of the array: {}", xs[1]);
  15. // `len` returns the size of the array
  16. println!("array size: {}", xs.len());
  17. // Arrays are stack allocated
  18. println!("array occupies {} bytes", mem::size_of_val(&xs));
  19. // Arrays can be automatically borrowed as slices
  20. println!("borrow the whole array as a slice");
  21. analyze_slice(&xs);
  22. // Slices can point to a section of an array
  23. println!("borrow a section of the array as a slice");
  24. analyze_slice(&ys[1 .. 4]);
  25. // Out of bound indexing yields a panic
  26. println!("{}", xs[5]);
  27. }