我是 Rust 新手,我正在使用 Rust Book 来学习它。
最近,我在那里发现了这个功能:
// Returns the number of characters in the first
// word of the given 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()
}
Run Code Online (Sandbox Code Playgroud)
如您所见,作者在这里使用 String::as_bytes() 方法来枚举字符串。然后,他们将 char ' ' 转换为 u8 类型,以检查我们是否已到达第一个单词的末尾。
据我所知,还有另一种选择,看起来更好:
fn first_word(s: &String) -> usize {
for (i, item) in s.chars().enumerate() {
if item == ' ' {
return i; …Run Code Online (Sandbox Code Playgroud) rust ×1