学习Rust的第8天:Slicing

发布于:2024-04-20 ⋅ 阅读:(102) ⋅ 点赞:(0)

Slices in Rust allow us to reference contiguous sequences of elements in collections, offering more granular control over data manipulation. We explored how to create slices using array and string literals, understanding the range syntax and its exclusivity.

Rust中的切片允许我们引用集合中连续的元素序列,从而对数据操作提供更细粒度的控制。我们探讨了如何使用数组和字符串字面量创建切片,了解范围语法及其排他性。

Introduction 介绍

In rust, Slices allow you to refer to a contiguous sequence of elements in a collection of items, rather than the whole collection.
在rust中,Slices允许你引用一个项目集合中的一个连续的元素序列,而不是整个集合。

let numbers = [1, 2, 3, 4, 5];
let slice = &numbers[1..4]; // [2, 3, 4]
  • [1..4] starts at index 1 and ends at 3. 4 is exclusive.
    [1..4] 开始于索引1,结束于索引3。四是排他性。
  • [1..=4] starts at index 1 and ends at 4.
    [1..=4] 开始于索引1,结束于索引4。

Visual representation 视觉表示

String slices 字符串slice

fn first_word(s: &String) -> usize{
  let bytes = s.as_bytes(); 
  for (i, &item) in bytes.iter().enumerate(){
    if item == b' ' {
      return i;
    }
  }
  s.len()
}

This function takes in a string as a parameter and returns the index of the first space character.
这个函数接受一个字符串作为参数,并返回第一个 space 字符的索引。

  • fn first_word(s: &String) -> usize {: Defines a function to find the index of the first space character in a string.
    fn first_word(s: &String) -> usize { :定义一个函数来查找字符串中第一个空格字符的索引。
  • let bytes = s.as_bytes();: Converts the string into an array of bytes.
    let bytes = s.as_bytes(); :将字符串转换为字节数组。
  • for (i, &item) in bytes.iter().enumerate() {: Iterates over each byte in the array, keeping track of its index.
    for (i, &item) in bytes.iter().enumerate() { :遍历数组中的每个字节,跟踪其索引。
  • if item == b' ' { return i; }: Returns the index if a space character is found.
    if item == b' ' { return i; } :如果找到空格字符,则返回索引。
  • s.len(): Returns the length of the string if no space character is found, indicating the entire string is the "first word."
    s.len() :如果没有找到空格字符,则返回字符串的长度,表示整个字符串是“第一个单词”。“

It compiles successfully and gives no error but there are two things wrong with this function.
它编译成功,没有错误,但这个函数有两个错误。

fn main(){
  let s: String = String::from("Hello World");
  let word_index: usize = first_word(&s); // word_index = 5
  s.clear(); //The string is now empty
  //word_index is still 5 but the string is empty hence the value is useless
}

The second problem is with the way its implemented. If we were to get the second word with this implementation our function definitation would look something like this
第二个问题是执行的方式。如果我们在这个实现中得到第二个词,我们的函数定义将如下所示

fn second_word(s: &String) -> (usize, usize){
 ...
}

String slices work the same as slices they’re just on strings, Example :
字符串切片的工作原理与切片相同,它们只是在字符串上,例如:

fn main(){
  let s: String = String::from("Hello World");
  let hello: &str = &s[0..5];
  println!("{}",hello);
}

Now that we have a basic understanding of our function and string slices. let’s modify our function.
现在我们对函数和字符串切片有了基本的了解。让我们修改我们的函数。

fn first_word(s: &str) -> &str {
  let bytes: &[u8] = s.as_bytes();

  for(i, &item) in bytes.iter().enumerate() {
    if item == b' '{
      return &s[0..i];
    }
  }
  &s[..]
}
fn main(){
    let string: &str = "Hello World!";
    let word = first_word(&string);
    println!("{}",word);
}
  • fn first_word(s: &str) -> &str {: Defines a function to find and return the first word in a string slice.
    fn first_word(s: &str) -> &str { :定义一个函数来查找并返回字符串切片中的第一个单词。
  • let bytes: &[u8] = s.as_bytes();: Converts the string slice into a byte slice.
    let bytes: &[u8] = s.as_bytes(); :将字符串切片转换为字节切片。
  • for(i, &item) in bytes.iter().enumerate() {: Iterates over each byte in the byte slice, keeping track of its index.
    for(i, &item) in bytes.iter().enumerate() { :遍历字节切片中的每个字节,跟踪其索引。
  • if item == b' ' { return &s[0..i]; }: Returns a reference to a substring from index 0 to i if a space character is found, representing the first word.
    if item == b' ' { return &s[0..i]; } :如果找到空格字符,则返回对索引 0 到 i 的子字符串的引用,表示第一个单词。
  • &s[..]: Returns a reference to the entire original string slice if no space character is found, implying the entire string is the "first word."
    &s[..] :如果没有找到空格字符,则返回对整个原始字符串切片的引用,这意味着整个字符串是“第一个单词”。“

For practice purposes, You should create a function which gets the second word using this approach. All the best!
为了练习的目的,你应该创建一个函数,使用这种方法获取第二个单词。祝一切顺利!


网站公告

今日签到

点亮在社区的每一天
去签到