Rust Slice:断章取义的艺术
切片 (Slice) 是一个没有所有权的数据类型。切片允许你引用集合中一段连续的元素序列,而不是引用整个集合。
🍰 字符串切片 (&str)
String 是完整的字符串对象,而 &str 通常是字符串切片。
fn main() {
let s = String::from("Hello world");
let hello = &s[0..5]; // 引用前5个字节
let world = &s[6..11]; // 引用第6到11个字节
println!("{}, {}", hello, world);
}
📏 Range 语法 (..)
[0..2]: 包含 0,不包含 2。[0..=2]: 包含 0,也包含 2。[..2]: 从头开始到 2。[3..]: 从 3 开始到结尾。[..]: 整个切片。
🚫 切片防止悬垂引用
因为切片是对原数据的引用,如果原数据被销毁或修改了,切片就会失效。Rust 编译器会保证这一点。
fn main() {
let mut s = String::from("hello");
let word = &s[..]; // word 借用了 s
// s.clear(); // ❌ 报错!因为 s 还在被 word 借用,不能修改!
println!("Word is: {}", word);
}
🧩 其他类型的切片
切片不仅用于字符串,还可以用于数组。
fn main() {
let a = [1, 2, 3, 4, 5];
let slice = &a[1..3]; // 类型是 &[i32]
assert_eq!(slice, &[2, 3]);
}