CS3984 Computer Systems in Rust



Slices

  1. A slice is a dynamically sized view into a contiguous sequence of elements.

  2. The type of a slice of elements of type t is [t] (eg. a slice of u32 is [u32]).

  3. Slices can be created through bracket notation and a range rather than an index (eg. array[5..6]).

  4. Since slices do not have a known size at compile time, they cannot be assigned to local variables.

fn main() {
    let array = [1, 2, 3, 4, 5];
    // Err: the size for values of type `[i32]` cannot be known at compilation time
    let slice: [i32] = array[1..2];
}


Slice References

  1. Slices are usually seen in its borrowed form as a slice reference / shared slice / reference to a slice.

  2. The type of a slice reference is &[T].

  3. A slice reference is a fat pointer; in addition to being a regular reference, a slice reference contains the length of the slice it points to.

fn main() {
    let array = [1, 2, 3, 4, 5];
    let slice: &[i32] = &array[1..2];
}


  1. A mutable slice reference, &mut [T], allows mutating the elements the slice reference points to.

String Slices

  1. The primitive string type is the string slice str, and is a slice of bytes (u8) in the UTF-8 encoding.

  2. String slices are also commonly used in its borrowed form, &str.

  3. String literals are string slices.

fn main() {
    // Owned String
    let str_owned: String = String::from("Hello world!");
    let str_owned_ref: &str = &str_owned;

    // String literal
    let str_literal: &str = "Hello world!";
}