Rust 编程中的切片


Rust 中的切片是相同数据类型 T 的元素集合,但与数组不同,不必在编译时就知道它们的长度。

在 Rust 中,切片是一个由两个单词构成对象,其中第一个单词实际上指向数据,第二个单词只是切片长度。

切片比数组安全得多,并且可以在不进行复制的情况下高效地访问数组。切片由数组、字符串创建。它们既可以是可变的,也可以是不可变的。切片通常是指数组或字符串的切片。

范例

 在线演示

fn main() {
   let xs: [i32; 5] = [1, 2, 3, 4, 5];
   let slice = &xs[1..5];
   println!("first element of the slice: {}", slice[0]);
   println!("the slice has {} elements", slice.len());
}

在上例中,我们获取一个数组的切片,当我们对数组进行切片时,我们必须在 [] 括号中提供起始和结束索引,以指定我们想要在我们的切片中包含的数组元素。

输出

first element of the slice: 2
the slice has 4 elements

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

字符串的切片

fn main() {
   let str= String::from("Hey Tuts!!");
   let hello = &str[0..5];
   let hello=&str[..5];
   println!("the hello contains {}", hello);
}

如果我们仅想要考虑从第一个元素开始的切片,那么我们可以避免使用第一个整数,只需在 [] 括号中键入结束索引。

输出

the hello contains Hey T

范例

但是,如果我们想要从一个索引切片到字符串末尾,我们可以这样做。

fn main() {
   let str= String::from("Hey Tuts!!");
   let hello = &str[3..];
   let hello=&str[3..];
   println!("the hello contains {}", hello);
}

输出

the hello contains Tuts!!

更新于: 03-04-2021

189 浏览量

开始您的职业

完成课程获得认证

开始
广告