Easy Tutorial
❮ Rust File Io Rust Println ❯

Rust Slice Type

A slice is a reference to a part of a data value.

The term "slice" often appears in biology classes when we need to obtain a slice from a biological specimen for observation under a microscope. In Rust, the concept is similar, but instead of taking a physical slice, it references a portion of the data.

String Slice

The simplest and most commonly used type of data slice is the string slice.

Example

fn main() {
    let s = String::from("broadcast");

    let part1 = &s[0..5];
    let part2 = &s[5..9];

    println!("{}={}+{}", s, part1, part2);
}

Running result:

broadcast=broad+cast

The diagram above explains the principle of string slicing (Note: Rust's string type essentially records the starting position and length of the characters in memory; we will understand this for now).

The syntax for ranges using .. was introduced in the loop section. x..y represents the mathematical meaning of [x, y). .. can be used without operands on both sides:

..y is equivalent to 0..y
x.. is equivalent to position x to the end of the data
.. is equivalent to position 0 to the end

Note: For now,尽量避免在字符串中使用非英文字符,因为编码问题。具体原因将在"字符串"章节中叙述。

A string that is sliced and referenced cannot have its value changed:

Example

fn main() {
    let mut s = String::from("tutorialpro");
    let slice = &s[0..3];
    s.push_str("yes!"); // Error
    println!("slice = {}", slice);
}

This program is incorrect.

s is partially referenced, and its value cannot be changed.

Actually, you might wonder why you have to write String::from("tutorialpro") every time you use a string. Why not just write "tutorialpro" directly?

By now, we must distinguish between these two concepts. In Rust, there are two commonly used string types: str and String. str is a core language type in Rust, which is the string slice we have been discussing in this chapter, often appearing in reference form (&str).

Any string literal enclosed in double quotes has the type &str:

let s = "hello";

Here, s is a variable of type &str.

String is a data type provided by Rust's standard library, which is more functional—it supports operations like appending and clearing strings. Besides having a starting position and length, String also has a capacity property.

Both String and str support slicing, and the result of slicing is &str type data.

Note: The result of slicing must be a reference type, and the developer must explicitly specify this:

let slice = &s[0..3];

There is a quick way to convert a String to &str:

let s1 = String::from("hello");
let s2 = &s1[..];

Non-String Slices

Besides strings, other linear data structures also support slicing, such as arrays:

Example

fn main() {
    let arr = [1, 3, 5, 7, 9];
    let part = &arr[0..3];
    for i in part.iter() {
        println!("{}", i);
    }
}

Running result:

1
3
5
❮ Rust File Io Rust Println ❯