Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Slice

The slice type

  • Slice allows to reference a contiguous sequence of elements in collections (String, arrays, etc..)
  • Slice does not have ownership.

String slice

  • Starting index refers to the first position in the slice (indexing starts with 0) and is inclusive
  • Ending index refers to a position that is one more than the last position of the slice and is exclusive
  • Its type is &str and is immutable
let s = String::from("hello world");

    let hello = &s[0..5]; // "hello"
    let world = &s[6..11]; // "world"

    // "hello", 0 at the beginning can be ommitted
    let hello = &s[..5]; 

    // "world", going up to the last byte of the String
    let world = &s[6..]; 

    // "hello world", takes a slice of the entire String
    let hello_world = &s[..]; 

String literals

  • String literals are hardcoded in the binary
  • String literal is a slice pointing to that specific point in the binary
  • Its type is &str -> it is immutable reference
// string literal of type &str (string slice), it's immutable
let s = "Hello, world!";

Other slices - array

let a = [1, 2, 3, 4, 5];

// slice is of type &[i32]
let slice = &a[1..3];

assert_eq!(slice, &[2, 3]);