Slices

https://doc.rust-lang.org/book/ch04-03-slices.html

  • A string slice is a reference to a portion of a string. Type signature is &str.

  • Implemented as a pointer to a particular string index, coupled with a length.

  • If you have a string slice, you can’t obtain a mutable reference to the string, so the slice is guaranteed to be valid wrt. the underlying string.

  • For this code:

    let s = String::from("hello world");
    let hello = &s[0..5];
    let world = &s[6..11];
    

    The underlying reference looks like:

  • Get a slice of the entire string with &s[..]. This is semantically identical to &s and automatic coercion occurs, so you can pass &s to a function that expects &str.

  • You can get slices of any type:

    let a = [1, 2, 3, 4, 5];
    
    // `slice` has the type &[i32]
    let slice = &a[1..3];
    
Edit