Rust String slicing


Example

fn main() {
    let english = "Hello, World!";

    println!("{}", &english[0..5]); // Prints "Hello"
    println!("{}", &english[7..]);  // Prints "World!"
}

Note that we need to use the & operator here. It takes a reference and thus gives the compiler information about the size of the slice type, which it needs to print it. Without the reference, the two println! calls would be a compile-time error.

Warning: Slicing works by byte offset, not character offset, and will panic when bounds are not on a character boundary:

fn main() {
    let icelandic = "Halló, heimur!"; // note that “ó” is two-byte long in UTF-8

    println!("{}", &icelandic[0..6]); // Prints "Halló", “ó” lies on two bytes 5 and 6
    println!("{}", &icelandic[8..]);  // Prints "heimur!", the “h” is the 8th byte, but the 7th char
    println!("{}", &icelandic[0..5]); // Panics!
}

This is also the reason why strings don't support simple indexing (eg. icelandic[5]).