问题:C语言缺乏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()
}
fn main() {
let mut s = String::from("hello world");
let word = first_word(&s); // word 的值为 5
s.clear(); // 这清空了字符串,使其等于 ""
// word 在此处的值仍然是 5,
// 但是没有更多的字符串让我们可以有效地应用数值 5。word 的值现在完全无效!
}
这个程序编译时没有任何错误,而且在调用 s.clear()
之后使用 word
也不会出错。因为 word
与 s
状态完全没有联系,所以 word
仍然包含值 5
。可以尝试用值 5
来提取变量 s
的第一个单词,不过这是有 bug 的,因为在我们将 5
保存到 word
之后 s
的内容已经改变。
我们不得不时刻担心 word
的索引与 s
中的数据不再同步,这很啰嗦且易出错!如果编写这么一个 second_word
函数的话,管理索引这件事将更加容易出问题。
字符串 slice(string slice)是 String
中一部分值的引用,它看起来像这样:
fn main() {
let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..11];
}