1
头图

slice

slice is a non-ownership data type provided in Rust that is a reference to a specific location of some type (String, Array...).

  • In Rust, a string literal is a slice type, a reference to a value at a specific location in the binary, and an immutable reference
  • The symbol of slice type is represented by &str

Next we look at how to create a slice

// 1.使用字面值创建切片
let slice = "haha";

// 2.使用 range 对 String 进行切片
let s = String::from("hello world");

let sclice_s = &s[0..5]; // "hello"
// 如果是从开头到结尾进行切片,则可以简写
let sclice_s_all = &s[..]; // "hello world"

Why use slices

For beginners, there may be such a question, why use slices, and what problems are slices used to solve? To understand these problems, we should first understand some application scenarios, which can be helpful for subsequent analysis. Suppose now we want to design such a function, its function is to extract all characters before the first space in a string, if there is no space, return the whole string, such as ("hello world" extracts "hello"), but now we Slices cannot be used, only the index of the key position can be considered

  • Match the first occurrence of a space from a string and return its index
  • Returns the length of the string if no spaces are matched

Next we look at the Rust implementation

fn main() {
    let str = String::from("hello world");

    let index = get_space_index(&str);

    println!("index is {}", index); // index is 5
}

fn get_space_index(s: &String) -> usize {
    // 将字符串转为字符数组
    let arr = s.as_bytes();

    for (i, &item) in arr.iter().enumerate() {
        if item == b' ' {
            return i;
        }
    }

    s.len()
}

The above example can achieve the index of the first space, and we can also use this index to meet the requirements later, but the problem with this method is that the index we get is not strongly associated with the string, if we use the index before, If the target string is accidentally modified, the index loses its meaning.

Based on the above problems, we should use slices to establish a strong association with the target string, and take advantage of the that slices are immutable references , and let the Rust compiler help us check Modify target string values through mutable references Unreasonable operation (for students who have doubts here, you can read my previous sharing - " 03-Citation and Borrowing ")

Next we use slices to achieve the initial requirement

fn main() {
    let str = String::from("hello world");

    let first_word = slice_first_word(&str[..]);

    println!("{}", first_word); // hello
}

fn slice_first_word(s: &str) -> &str {
    // 将字符串转为字符数组
    let arr = s.as_bytes();

    for (i, &item) in arr.iter().enumerate() {
        // 判断当前位是否是空格
        if item == b' ' {
            return &s[..i];
        }
    }

    &s[..]
}

Slices of other data types

array

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

let slice = &arr[1..3];

println!("{:?}", slice); // [2,3]

木木剑光
2.2k 声望2k 粉丝

Ant Design 社区贡献者