这是用户在 2025-1-12 2:01 为 https://doc.rust-lang.org/book/ch04-03-slices.html 保存的双语快照页面,由 沉浸式翻译 提供双语支持。了解如何保存?

切片类型  

切片允许你引用集合中一段连续的元素序列,而不是整个集合。切片是一种引用,因此它没有所有权。

这是一个小的编程问题:编写一个函数,该函数接受一个由空格分隔的单词字符串,并返回它在该字符串中找到的第一个单词。如果函数在字符串中没有找到空格,那么整个字符串必须是一个单词,因此应返回整个字符串。

让我们通过编写不使用切片的函数签名来理解切片将解决的问题:

fn first_word(s: &String) -> ?

first_word 函数有一个 &String 作为参数。我们不想要所有权,所以这没问题。但我们应该返回什么呢?我们没有一个方法来讨论字符串的一部分。不过,我们可以返回单词末尾的索引,用空格表示。让我们试试这个,如代码清单 4-7 所示。

文件名: src/main.rs  
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() } fn main() {}
清单 4-7:返回 String 参数中字节索引值的 first_word 函数

因为我们需要逐个遍历 String 元素并检查某个值是否为空格,所以我们将使用 as_bytes 方法将 String 转换为字节数组。

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() } fn main() {}

接下来,我们使用 iter 方法在字节数组上创建一个迭代器:

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() } fn main() {}

我们将在第 13 章更详细地讨论迭代器。现在只需知道, iter 是一个返回集合中每个元素的方法,而 enumerate 则包装了 iter 的结果,并将每个元素作为元组的一部分返回。从 enumerate 返回的元组的第一个元素是索引,第二个元素是对元素的引用。这比我们自己计算索引要方便一些。

因为 ` enumerate ` 方法返回一个元组,我们可以使用模式来解构这个元组。我们将在第 6 章详细讨论模式。在 ` for ` 循环中,我们指定了一个模式,其中 ` i ` 用于元组中的索引,` &item ` 用于元组中的单个字节。因为我们从 ` .iter().enumerate() ` 获取了对元素的引用,所以在模式中使用了 ` & `。

for 循环内部,我们通过使用字节字面量语法来搜索表示空格的字节。如果找到空格,我们返回其位置。否则,我们通过使用 s.len() 返回字符串的长度。

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() } fn main() {}

我们现在有了一个方法来找出字符串中第一个单词结尾的索引,但这里有一个问题。我们单独返回了一个 usize ,但它只有在 &String 的上下文中才是一个有意义的数字。换句话说,因为它是一个与 String 分离的值,所以不能保证它在未来仍然有效。考虑一下清单 4-8 中使用清单 4-7 中 first_word 函数的程序。

文件名: src/main.rs  
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() } fn main() { let mut s = String::from("hello world"); let word = first_word(&s); // word will get the value 5 s.clear(); // this empties the String, making it equal to "" // word still has the value 5 here, but there's no more string that // we could meaningfully use the value 5 with. word is now totally invalid! }
列表 4-8:存储调用 first_word 函数的结果,然后更改 String 内容

该程序编译时没有任何错误,即使我们在调用 s.clear() 后使用 word ,它也会如此。因为 words 的状态完全无关, word 仍然包含值 5 。我们可以使用该值 5 与变量 s 尝试提取第一个单词,但这将是一个错误,因为自我们在 word 中保存 5 以来, s 的内容已经发生了变化。

担心 word 中的索引与 s 中的数据不同步既繁琐又容易出错!如果我们编写一个 second_word 函数,管理这些索引会更加脆弱。它的签名必须如下所示:

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

现在我们正在跟踪一个起始索引和一个结束索引,并且我们还有更多从特定状态的数据计算得出的值,但这些值与状态本身毫无关联。我们有三个互不相关的变量在四处游荡,需要保持同步。

幸运的是,Rust 针对这个问题提供了一个解决方案:字符串切片。

字符串切片  

字符串切片是对 String 部分内容的引用,它看起来像这样:

fn main() { let s = String::from("hello world"); let hello = &s[0..5]; let world = &s[6..11]; }

与引用整个 String 不同, hello 是对 String 一部分的引用,这部分在额外的 [0..5] 位中指定。我们通过在括号内指定 [starting_index..ending_index] 来创建切片,其中 starting_index 是切片中的第一个位置, ending_index 是切片中最后一个位置的下一个位置。在内部,切片数据结构存储了切片的起始位置和长度,这对应于 ending_index 减去 starting_index 。因此,在 let world = &s[6..11]; 的情况下, world 将是一个切片,它包含指向 s 索引 6 处字节的指针,长度值为 5

图 4-7 以图示形式展示了这一点。

Three tables: a table representing the stack data of s, which points
to the byte at index 0 in a table of the string data "hello world" on
the heap. The third table rep-resents the stack data of the slice world, which
has a length value of 5 and points to byte 6 of the heap data table.

图 4-7:字符串切片引用 String 的一部分

使用 Rust 的 .. 范围语法时,如果你想从索引 0 开始,可以省略两个点之前的值。换句话说,以下两种写法是等价的:

#![allow(unused)] fn main() { let s = String::from("hello"); let slice = &s[0..2]; let slice = &s[..2]; }

同样地,如果您的切片包含 String 的最后一个字节,您可以省略末尾的数字。这意味着以下内容是相等的:

#![allow(unused)] fn main() { let s = String::from("hello"); let len = s.len(); let slice = &s[3..len]; let slice = &s[3..]; }

你也可以省略这两个值来获取整个字符串的切片。因此,这些是相等的:

#![allow(unused)] fn main() { let s = String::from("hello"); let len = s.len(); let slice = &s[0..len]; let slice = &s[..]; }

注意:字符串切片的范围索引必须位于有效的 UTF-8 字符边界上。如果你尝试在多字节字符的中间创建字符串切片,你的程序将会出错并退出。为了介绍字符串切片的目的,我们在本节中仅假设使用 ASCII 编码;关于 UTF-8 处理的更深入讨论,请参见第 8 章中的“使用字符串存储 UTF-8 编码文本”部分。

考虑到所有这些信息,让我们重写 first_word 以返回一个切片。表示“字符串切片”的类型写作 &str

文件名: src/main.rs  
fn first_word(s: &String) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] } fn main() {}

我们以与清单 4-7 相同的方式获取单词末尾的索引,即通过查找第一个空格的出现位置。当我们找到一个空格时,我们使用字符串的起始位置和空格的索引作为起始和结束索引来返回一个字符串切片。

现在当我们调用 first_word 时,我们得到一个与底层数据绑定的单一值。该值由对切片起始点的引用和切片中元素的数量组成。

返回切片也适用于 second_word 函数:

fn second_word(s: &String) -> &str {

我们现在有了一个更不容易出错的直接 API,因为编译器会确保对` String `的引用保持有效。还记得清单 4-8 中程序的 bug 吗?当我们获取到第一个单词末尾的索引后,却清空了字符串,导致索引无效。那段代码逻辑上是错误的,但并没有立即显示任何错误。如果我们继续尝试使用已清空字符串的第一个单词索引,问题会在之后显现。切片使得这种 bug 不可能发生,并让我们更早地知道代码存在问题。使用` first_word `的切片版本会在编译时抛出错误:

文件名: src/main.rs  
fn first_word(s: &String) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] } fn main() { let mut s = String::from("hello world"); let word = first_word(&s); s.clear(); // error! println!("the first word is: {word}"); }

以下是编译器错误:

$ cargo run Compiling ownership v0.1.0 (file:///projects/ownership) error[E0502]: cannot borrow `s` as mutable because it is also borrowed as immutable --> src/main.rs:18:5 | 16 | let word = first_word(&s); | -- immutable borrow occurs here 17 | 18 | s.clear(); // error! | ^^^^^^^^^ mutable borrow occurs here 19 | 20 | println!("the first word is: {word}"); | ------ immutable borrow later used here For more information about this error, try `rustc --explain E0502`. error: could not compile `ownership` (bin "ownership") due to 1 previous error

回忆一下借用规则,如果我们有一个不可变引用,我们就不能同时获取一个可变引用。因为 clear 需要截断 String ,它需要获取一个可变引用。调用 clear 之后的 println! 使用了 word 中的引用,因此不可变引用在此时必须仍然有效。Rust 不允许 clear 中的可变引用和 word 中的不可变引用同时存在,因此编译失败。Rust 不仅使我们的 API 更易于使用,还在编译时消除了整个类别的错误!

字符串字面量作为切片

回想一下,我们讨论过字符串字面量存储在二进制文件中。现在我们已经了解了切片,我们可以正确理解字符串字面量了:

#![allow(unused)] fn main() { let s = "Hello, world!"; }

这里的 s 类型是 &str :它是一个指向二进制特定点的切片。这也是为什么字符串字面量是不可变的; &str 是一个不可变引用。

String Slices 作为参数

知道可以对字面量和 String 值进行切片后,我们还可以对 first_word 进行一项改进,那就是它的签名:

fn first_word(s: &String) -> &str {

更有经验的 Rustacean 会写出如代码清单 4-9 所示的签名,因为它允许我们在 &String 值和 &str 值上使用相同的函数。

fn first_word(s: &str) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] } fn main() { let my_string = String::from("hello world"); // `first_word` works on slices of `String`s, whether partial or whole let word = first_word(&my_string[0..6]); let word = first_word(&my_string[..]); // `first_word` also works on references to `String`s, which are equivalent // to whole slices of `String`s let word = first_word(&my_string); let my_string_literal = "hello world"; // `first_word` works on slices of string literals, whether partial or whole let word = first_word(&my_string_literal[0..6]); let word = first_word(&my_string_literal[..]); // Because string literals *are* string slices already, // this works too, without the slice syntax! let word = first_word(my_string_literal); }
列表 4-9:通过为 s 参数的类型使用字符串切片来改进 first_word 函数

如果我们有一个字符串切片,我们可以直接传递它。如果我们有一个 String ,我们可以传递 String 的切片或 String 的引用。这种灵活性利用了 deref 强制转换,这是我们在第 15 章的“函数和方法的隐式 Deref 强制转换”部分将介绍的一个特性。

定义一个函数以接受字符串切片而不是对 String 的引用,使我们的 API 更加通用和有用,同时不会失去任何功能:

文件名: src/main.rs  
fn first_word(s: &str) -> &str { let bytes = s.as_bytes(); for (i, &item) in bytes.iter().enumerate() { if item == b' ' { return &s[0..i]; } } &s[..] } fn main() { let my_string = String::from("hello world"); // `first_word` works on slices of `String`s, whether partial or whole let word = first_word(&my_string[0..6]); let word = first_word(&my_string[..]); // `first_word` also works on references to `String`s, which are equivalent // to whole slices of `String`s let word = first_word(&my_string); let my_string_literal = "hello world"; // `first_word` works on slices of string literals, whether partial or whole let word = first_word(&my_string_literal[0..6]); let word = first_word(&my_string_literal[..]); // Because string literals *are* string slices already, // this works too, without the slice syntax! let word = first_word(my_string_literal); }

其他切片  

字符串切片,正如你所想象的,是特定于字符串的。但也有一种更通用的切片类型。考虑这个数组:

#![allow(unused)] fn main() { let a = [1, 2, 3, 4, 5]; }

正如我们可能想要引用字符串的一部分一样,我们也可能想要引用数组的一部分。我们可以这样做:

#![allow(unused)] fn main() { let a = [1, 2, 3, 4, 5]; let slice = &a[1..3]; assert_eq!(slice, &[2, 3]); }

这个切片的类型是 &[i32] 。它的工作方式与字符串切片相同,通过存储对第一个元素的引用和长度来实现。你将使用这种切片来处理各种其他集合。我们将在第 8 章讨论向量时详细讨论这些集合。

摘要  

所有权、借用和切片的概念确保了 Rust 程序在编译时的内存安全。Rust 语言让你像其他系统编程语言一样控制内存使用,但当数据所有者离开作用域时自动清理数据,意味着你无需编写和调试额外代码即可获得这种控制。

所有权影响 Rust 中许多其他部分的工作方式,因此我们将在本书的其余部分进一步讨论这些概念。让我们继续第 5 章,看看如何将数据片段组合在一个 struct 中。