Slices

Slices

Rust by example - slices

A slice is a reference to a contiguous sequence of elements within a collection. This means it provides a view into a portion of an array, vector, or string, without owning the underlying data.

  • Slices are references, so they don't own the data they point to. This makes them efficient, as they avoid unnecessary copying.
  • They allow you to work with parts of a collection, enabling flexibility in data manipulation.
  • Slices are often created using the &[T] syntax, where T is the type of the elements in the slice. For string slices, the type is &str.

Common Use Cases

  • Accessing Subsets of Data: Slices are frequently used to access specific portions of arrays, vectors, or strings without copying the entire collection.
  • Function Arguments: Slices are often used as function arguments when you want to operate on a part of a collection.
  • String Manipulation: string slices (&str) are a common way to reference a string literal or a portion of a String.

Create Slices

Slices can be created by referencing a portion of a collection using a range. The range can be specified using [start..end], where start is the index of the first element to include, and end is the index of the element after the last one to include. If start is omitted, the slice starts from the beginning of the collection. If end is omitted, the slice extends to the end of the collection.

//! A slice is a view into a contiguous sequence of elements in a collection.
//! It does not own the data it points to.

/// Slices from an array:
fn array() {
    let array = [1, 2, 3, 4, 5];
    // Create a slice referencing elements at indices 1, 2, and 3
    let slice = &array[1..4];
    println!("{:?}", slice); // Output: [2, 3, 4]
    // `[..]` refers to the entire collection.
    let all = &array[..];
    println!("Entire array: {:?}", all);
}

/// Slices from `Vec`:
fn vectors() {
    let mut my_vector = vec![1, 2, 3, 4, 5];
    let slice = &my_vector[1..4]; // [2, 3, 4]
    println!("{:?}", slice);

    // Mutable slice
    let mutable_slice = &mut my_vector[2..];
    mutable_slice[0] = 10; // Modifies the original vector

    println!("{:?}", my_vector); // Output: [1, 2, 10, 4, 5]
}

/// String slices:
fn string() {
    let s = String::from("hello world");
    let hello: &str = &s[0..5]; // or &s[..5];
    let world = &s[6..11]; // or &s[6..];
    println!("{}", hello);
    println!("{}", world);
}

fn main() {
    array();
    vectors();
    string();
}

Useful Functions